bzoj 2818: Gcd
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; }
$\LARGE\sum ^{n}_{i=1}\sum ^{n}_{j=1}\gcd \left( i,j\right)$是质数
$\LARGE\sum ^{n}_{i=1}\sum ^{n}_{j=1}[\dfrac {\gcd \left( ij\right) }{P}==1]$
$\LARGE\sum ^{n}_{p}\sum ^{n,p}_{i=1}\sum ^{n/p}_{j=1}\left[ \gcd \left(i,j\right) ==1\right]$
$\LARGE\sum ^{n}_{p}\sum ^{n/p}_{i=1}\sum ^{n/p}_{j=1}\sum _{d|\gcd \left( i\cdot j\right) }\mu \left( d\right)$
$\LARGE\sum ^{n}_{p}\sum ^{n/p}_{d=1}\mu \left( d\right) \sum ^{n/P/d}_{i=1}\sum ^{n/p/d }_{j=1}$
$\LARGE\sum ^{n}_{p}\sum ^{n/P}_{d=1}\mu \left( d\right) \lfloor\dfrac {\dfrac {n}{p}}{d}\rfloor \lfloor\dfrac {\dfrac {n}{p}}{d}\rfloor$
#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; }