2820: YY的GCD
Description
Input
Output
Sample Input
10 10
100 100
Sample Output
2791
HINT
T = 10000
N, M <= 10000000
思路:
题目中描述的式子即为:
$sumlimits_{p}is[p]sumlimits_{i=1}^{N}sumlimits_{j=1}^{M}[gcd(i,j)=p]$
把$p$除到前面可以化简得 :
$sumlimits_{p}is[p]sumlimits_{i=1}^{lfloorfrac {N}{p}
floor}sumlimits_{j=1}^{lfloorfrac {M}{p}
floor}[gcd(i,j)=1]$
出现$[gcd(i,j)=1]$的形式,考虑莫比乌斯反演,化简得:
$sumlimits_{p}is[p]sumlimits_{i=1}^{lfloorfrac {N}{p}
floor}sumlimits_{j=1}^{lfloorfrac {M}{p}
floor}sumlimits_{d|gcd(i,j)}mu(d)$
把d提到前面得
$sumlimits_{p}is[p]sumlimits_{d=1}^{lfloorfrac {min(N,M)}{p}
floor}mu(d)sumlimits_{i=1}^{lfloorfrac {N}{dp}
floor}sumlimits_{j=1}^{lfloorfrac {M}{dp}
floor}$
设$Q = dp$ 枚举$Q$化简为
$sumlimits_{Q=1}^{min(N,M)}lfloorfrac{N}{Q}
floor lfloorfrac{M}{Q}
floorsumlimits_{p|Q}is[p]mu(frac{Q}{p})$
设函数$f(n) = sumlimits_{p|n}is[p]mu(frac{n}{p})$
考虑得出$f(n)$
有以下几种情况 :
1. 若 $f(n)$ 为质数
值即为$mu(1) = 1$
2. 若 $n % p == 0$ 则$f(n imes p)$可以化成$sumlimits_{d|n imes p}is[d]mu(frac{n imes p}{d})$
考虑当$d!=p$时$frac{n imes p}{d}$有多个$p$
对$sum$的贡献为0,所以此时$f(n imes p)=mu(n)$
1. 若 $n % p != 0$ , $f(n imes p)$可以化为$f(n) imes mu(p) + f(p) imes mu(n)$ 。我们又知道$mu(p) = -1$,$f(p) = 1$,所以$f(n imes p)=mu(n)-f(n)$
我们再处理一下前缀和, 老套路分$sqrt n$块计算。得到结果
```cpp
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 11000000;
bool np[N+10];
int mu[N+10], tot, pr[N+10], sum[N+10];
int f[N+10];
int t, n, m;
void init() {
mu[1]=1;
for(int i=2;i<=N;i++) {
if(!np[i]) {
pr[++tot]=i;
mu[i]=-1;
f[i]=1;
}
for(int j=1;j<=tot&&i*pr[j]<=N;j++) {
np[i*pr[j]]=1;
if(!(i%pr[j])) {
mu[i*pr[j]]=0;
f[i*pr[j]]=mu[i];
break;
}
mu[i*pr[j]]=-mu[i];
f[i*pr[j]]=mu[i]-f[i];
}
sum[i]=sum[i-1]+f[i];
}
}
void solve(int n, int m) {
if(n>m)swap(n,m);
int lst;
long long ans=0;
for(int i=1;i<=n;i=lst+1) {
lst = min(n/(n/i), m/(m/i));
ans+=1ll*(sum[lst]-sum[i-1])*(n/i)*(m/i);
}
printf("%lld
", ans);
}
int main() {
init();
scanf("%d",&t);
while(t--) {
scanf("%d%d",&n,&m);
solve(n,m);
}
}
BZOJ 2818 双倍经验
```