HDU 2588 思维 容斥

求满足$1<=X<=N ,(X,N)>=M$的个数,其中$N, M (2<=N<=1000000000, 1<=M<=N)$。

首先,假定$(x, n)=m$,那么 $(\frac{x}{n},\frac{n}{m})=1$,故$$ans=\sum_{i=m}^{n}\varphi(\frac{n}{i})$$

ん?遅い!

$$\sum_{i=m}^{n}\varphi(\frac{n}{i})=\sum\limits_{d|n}{\varphi(\frac{n}{d})}$$

其实还可以再优化下的吧?

 

/** @Date    : 2017-09-20 21:55:29
  * @FileName: HDU 2588 思维 容斥 或 欧拉函数.cpp
  * @Platform: Windows
  * @Author  : Lweleth (SoungEarlf@gmail.com)
  * @Link    : https://github.com/
  * @Version : $Id$
  */
#include <bits/stdc++.h>
#define LL long long
#define PII pair<int ,int>
#define MP(x, y) make_pair((x),(y))
#define fi first
#define se second
#define PB(x) push_back((x))
#define MMG(x) memset((x), -1,sizeof(x))
#define MMF(x) memset((x),0,sizeof(x))
#define MMI(x) memset((x), INF, sizeof(x))
using namespace std;

const int INF = 0x3f3f3f3f;
const int N = 1e5+20;
const double eps = 1e-8;

LL pri[N];
int vis[N];
int c = 0;

void prime()
{
	MMF(vis);
	for(int i = 2; i < N; i++)
	{
		if(!vis[i]) pri[c++] = i;
		for(int j = 0; j < c && i * pri[j] < N; j++)
		{
			vis[i * pri[j]] = 1;
			if(i % pri[j] == 0) break;
		}
	}
}

LL get_phi(LL x)
{
	LL ans = x;
	for(int i = 0; i < c && pri[i] <= x / pri[i]; i++)
	{
		if(x % pri[i] == 0)
		{
			while(x % pri[i] == 0)
				x /= pri[i];
			ans = ans / pri[i] * (pri[i] - 1);
		}
	}
	if(x > 1)
		ans = ans / x * (x - 1);
	return ans;
}

int main()
{
	int T;
	cin >> T;
	prime();
	while(T--)
	{
		LL n, m;
		scanf("%lld%lld", &n, &m);
		LL t = n;
		LL ans = 0;
		for(LL i = 1; i <= t / i; i++)
		{
			if(t % i == 0)
			{
				//cout << i << t/i << endl;
				if(i >= m)
					ans += get_phi(n / i);
				if(t / i != i && t / i >= m)
					ans += get_phi(n / (t / i));
			}
		}
		printf("%lld\n", ans);
	}
    return 0;
}
posted @ 2017-09-21 00:35  Lweleth  阅读(114)  评论(0编辑  收藏  举报