BZOJ2818 GCD 【莫比乌斯反演】
2818: Gcd
Time Limit: 10 Sec Memory Limit: 256 MB
Submit: 6826 Solved: 3013
[Submit][Status][Discuss]
Description
给定整数N,求1<=x,y<=N且Gcd(x,y)为素数的
数对(x,y)有多少对.
Input
一个整数N
Output
如题
Sample Input
4
Sample Output
4
HINT
hint
对于样例(2,2),(2,4),(3,3),(4,2)
1<=N<=10^7
题解
一般gcd一堆求和都是莫比乌斯
我们设f(n)表示gcd等于n的对数
我们设F(n)表示n|gcd的对数
则有
至此我们可以枚举T,之后计算后边的和式就好了
其实后边的和式可以预处理得到,我直接算也能过
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<bitset>
#define LL long long int
#define REP(i,n) for (int i = 1; i <= (n); i++)
#define Redge(u) for (int k = h[u]; k != -1; k = ed[k].nxt)
using namespace std;
const int maxn = 10000005,maxm = 100005,INF = 1000000000;
bitset<maxn> isn;
int prime[maxn],primei,miu[maxn],N;
void init(){
miu[1] = 1;
for (int i = 2; i <= N; i++){
if (!isn[i]) prime[++primei] = i,miu[i] = -1;
for (int j = 1; j <= primei && i * prime[j] <= N; j++){
isn[i * prime[j]] = true;
if (i % prime[j] == 0) {miu[i * prime[j]] = 0;break;}
miu[i * prime[j]] = -miu[i];
}
}
}
int main(){
cin>>N;
init();
LL ans = 0;
for (int i = 1; i <= primei; i++){
for (int j = 1; j <= N / prime[i]; j++)
ans += (LL) miu[j] * (N / prime[i] / j) * (N / prime[i] / j);
}
cout<<ans<<endl;
return 0;
}