BZOJ2820:YY的GCD(莫比乌斯反演)
Description
Input
Output
Sample Input
10 10
100 100
Sample Output
2791
HINT
T = 10000
N, M <= 10000000
Solution
以下均为n<m。
$\sum_{p\in prime}\sum_{a=1}^n\sum_{b=1}^m[gcd(a,b)=p]$
$\sum_{p\in prime}\sum_{a=1}^{\left \lfloor \frac{n}{p} \right \rfloor}\sum_{b=1}^{\left \lfloor \frac{m}{p} \right \rfloor}[gcd(a,b)=1]$
$\sum_{p\in prime}\sum_{a=1}^{\left \lfloor \frac{n}{p} \right \rfloor}\sum_{b=1}^{\left \lfloor \frac{m}{p} \right \rfloor}\sum_{d|gcd(a,b)}\mu(d)$
$\sum_{p\in prime}\sum_{d=1}^{\left \lfloor \frac{n}{p} \right \rfloor}\mu(d){\left \lfloor \frac{n}{pd} \right \rfloor}{\left \lfloor \frac{m}{pd} \right \rfloor}$
推到这和前面做过的几个题是一样的……然后就不会了QAQ……
设$pd=T$
$\sum_{T=1}^{n}{\left \lfloor \frac{n}{T} \right \rfloor}{\left \lfloor \frac{m}{T} \right \rfloor}\sum_{p|T}\mu(\frac{T}{p})$
j接下来只需要求出$\sum_{p|T}\mu(\frac{T}{p})$的前缀和就好了。暴力枚举每个质数去更新ta的倍数即可。
Code
1 #include<iostream> 2 #include<cstdio> 3 #define N (10000000) 4 using namespace std; 5 6 int T,n,m,vis[N+5],prime[N+5],mu[N+5],cnt; 7 long long sum[N+5]; 8 9 void Get_mu() 10 { 11 mu[1]=1; 12 for (int i=2; i<=N; ++i) 13 { 14 if (!vis[i]){prime[++cnt]=i; mu[i]=-1;} 15 for (int j=1; j<=cnt && prime[j]*i<=N; ++j) 16 { 17 vis[prime[j]*i]=true; 18 if (i%prime[j]==0) break; 19 mu[prime[j]*i]=-mu[i]; 20 } 21 } 22 for (int i=1; i<=cnt; ++i) 23 for (int j=1; j*prime[i]<=N; ++j) 24 sum[j*prime[i]]+=mu[j]; 25 for (int i=1; i<=N; ++i) sum[i]+=sum[i-1]; 26 } 27 28 long long Calc(int n,int m) 29 { 30 long long ans=0; if (n>m) swap(n,m); 31 for (int l=1,r; l<=n; l=r+1) 32 { 33 r=min(n/(n/l),m/(m/l)); 34 ans+=(sum[r]-sum[l-1])*(n/l)*(m/l); 35 } 36 return ans; 37 } 38 39 int main() 40 { 41 scanf("%d",&T); 42 Get_mu(); 43 while (T--) 44 { 45 scanf("%d%d",&n,&m); 46 printf("%lld\n",Calc(n,m)); 47 } 48 }