2818: Gcd
Time Limit: 10 Sec Memory Limit: 256 MBSubmit: 6863 Solved: 3035
[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(x,y)=p,则gcd(x/p,y/p)=1 法一:欧拉函数 枚举每个素数p,那么该素数p对答案的贡献为[1,n/p]中的有序互质对的个数 求[1,m]中有序互质对(i,j)的个数: 令j>=i 当i=j时,只有i=j=1互质; 当i<j时,确定j后,互质的个数为φ(j); 所以[1,m]中有序互质对个数=(Σ φ(j))*2-1 所以,欧拉筛筛出欧拉函数,求前缀和sum ans= Σ sum[n/p]*2-1 p为素数,p<=n */ #include<iostream> #include<cstdio> #define maxn 10000001 using namespace std; int n,prime[maxn],cnt,phi[maxn]; long long ans,sum[maxn]; bool v[maxn]; void euler(){ phi[1]=1; for(int i=2;i<=n;i++){ if(!v[i]){prime[++cnt]=i;v[i]=1;phi[i]=i-1;} for(int j=1;j<=cnt;j++){ if(prime[j]*i>n)break; v[prime[j]*i]=1; if(i%prime[j]==0){ phi[i*prime[j]]=phi[i]*prime[j]; break; } else phi[i*prime[j]]=phi[i]*(prime[j]-1); } } } int main(){ scanf("%d",&n); euler(); for(int i=1;i<=n;i++)sum[i]=sum[i-1]+phi[i]; for(int i=1;i<=cnt;i++)ans+=sum[n/prime[i]]*2-1; cout<<ans; }
$LARGEsum ^{n}_{i=1}sum ^{n}_{j=1}gcd left( i,j ight)$是质数
$LARGEsum ^{n}_{i=1}sum ^{n}_{j=1}[dfrac {gcd left( ij ight) }{P}==1]$
$LARGEsum ^{n}_{p}sum ^{n,p}_{i=1}sum ^{n/p}_{j=1}left[ gcd left(i,j ight) ==1 ight]$
$LARGEsum ^{n}_{p}sum ^{n/p}_{i=1}sum ^{n/p}_{j=1}sum _{d|gcd left( icdot j ight) }mu left( d ight)$
$LARGEsum ^{n}_{p}sum ^{n/p}_{d=1}mu left( d ight) sum ^{n/P/d}_{i=1}sum ^{n/p/d }_{j=1}$
$LARGEsum ^{n}_{p}sum ^{n/P}_{d=1}mu left( d ight) lfloordfrac {dfrac {n}{p}}{d} floor lfloordfrac {dfrac {n}{p}}{d} floor$
#include<iostream> #include<cstdio> #define maxn 10000010 using namespace std; bool v[maxn]; int n,cnt; long long ans,prime[maxn],mul[maxn]; void mobius(){ mul[1]=1; for(int i=2;i<=n;i++){ if(!v[i]){v[i]=1;prime[++cnt]=i;mul[i]=-1;} for(int j=1;j<=cnt;j++){ if(prime[j]*i>n)break; v[prime[j]*i]=1; if(i%prime[j]==0){ mul[i*prime[j]]=0; break; } else mul[i*prime[j]]=-mul[i]; } } } int main(){ scanf("%d",&n); mobius(); for(int i=1;i<=cnt;i++) for(int j=1;j<=n/prime[i];j++) ans+=mul[j]*(n/prime[i]/j)*(n/prime[i]/j); cout<<ans; }