【莫比乌斯反演】[CQBZOJ 2525]公约数
题目描述:
给定n请确定1<=x,y<=n中有多少gcd(x, y)=素数
详细参考请见:http://blog.csdn.net/jeremygjy/article/details/46360357
代码如下:
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const long long MAXN = 10000000;
bool notprime[MAXN+10];
int prime[MAXN+10], mu[MAXN+10], sum[MAXN+10];
long long GetAns(long long u){
long long ret = 0;
for(int i=1;i<=u;i++){
int last = u/(u/i);
ret += (sum[last] - sum[i-1]) * (u/i) * (u/i);
i = last;
}
return ret;
}
void Init(long long Max){
mu[1] = 1;
long long tmp;
for(long long i=2;i<=Max;i++){
if(!notprime[i]){
mu[i] = -1;
sum[i] = 1;
prime[++prime[0]] = i;
}
for(int j=1;j<=prime[0]&&(tmp=prime[j]*i)<=Max;j++){
notprime[tmp] = true;
if(i%prime[j] == 0){
mu[tmp] = 0;
sum[tmp] = mu[i];
break;
}
mu[tmp] = -mu[i];
sum[tmp] = mu[i] - sum[i];
}
}
for(int i=1;i<=Max;i++)
sum[i] += sum[i-1];
}
int main(){
long long n;
cin>>n;
Init(n);
cout<<GetAns(n)<<endl;
return 0;
}