正题
P1447
题目大意
给出n,m,求2×∑i=1n∑j=1m(gcd(i,j)−1)+n×m2\times \sum_{i=1}^n\sum_{j=1}^m(gcd(i,j)-1)+n\times m2×i=1∑nj=1∑m(gcd(i,j)−1)+n×m
解题思路
2×∑i=1n∑j=1m(gcd(i,j)−1)+n×m2×∑i=1n∑j=1mgcd(i,j)−n×m2\times \sum_{i=1}^n\sum_{j=1}^m(gcd(i,j)-1)+n\times m \\ 2\times \sum_{i=1}^n\sum_{j=1}^mgcd(i,j)-n\times m 2×i=1∑nj=1∑m(gcd(i,j)−1)+n×m2×i=1∑nj=1∑mgcd(i,j)−n×m
那么求出∑i=1n∑j=1mgcd(i,j)\sum_{i=1}^n\sum_{j=1}^mgcd(i,j)∑i=1n∑j=1mgcd(i,j)就好了
∑i=1n∑j=1mgcd(i,j)∑d=1nd∑i=1n/d∑j=1m/d[gcd(i,j)=1]∑d=1nd∑i=1n/d∑j=1m/d∑c∣i,c∣jμ(c)∑d=1nd∑c=1min(n/d,m/d)μ(c)×⌊ncd⌋×⌊mcd⌋\sum_{i=1}^n\sum_{j=1}^mgcd(i,j) \\ \sum_{d=1}^nd\sum_{i=1}^{n/d}\sum_{j=1}^{m/d}[gcd(i,j)=1] \\ \sum_{d=1}^nd\sum_{i=1}^{n/d}\sum_{j=1}^{m/d}\sum_{c|i,c|j}\mu(c) \\ \sum_{d=1}^nd\sum_{c=1}^{min(n/d,m/d)}\mu(c)\times\left\lfloor\frac{n}{cd}\right\rfloor\times\left\lfloor\frac{m}{cd}\right\rfloor i=1∑nj=1∑mgcd(i,j)d=1∑ndi=1∑n/dj=1∑m/d[gcd(i,j)=1]d=1∑ndi=1∑n/dj=1∑m/dc∣i,c∣j∑μ(c)d=1∑ndc=1∑min(n/d,m/d)μ(c)×⌊cdn⌋×⌊cdm⌋
考虑枚举cd,设k=cd
∑k=1n⌊nk⌋⌊mk⌋∑d∣kd×μ(k/d)\sum_{k=1}^n\left\lfloor\frac{n}{k}\right\rfloor\left\lfloor\frac{m}{k}\right\rfloor\sum_{d|k}d\times\mu(k/d) k=1∑n⌊kn⌋⌊km⌋d∣k∑d×μ(k/d)
因为有μ×id=φ\mu\times id=\varphiμ×id=φ
所以原式等于
∑k=1n⌊nk⌋⌊mk⌋φ(k)\sum_{k=1}^n\left\lfloor\frac{n}{k}\right\rfloor\left\lfloor\frac{m}{k}\right\rfloor\varphi(k)k=1∑n⌊kn⌋⌊km⌋φ(k)
可以整除分块
时间复杂度 O(n+n)O(n+\sqrt{n})O(n+n)
code
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define ll long long
#define N 100100
using namespace std;
ll n,m,w,ans,p[N],phi[N],prime[N];
const ll MX=1e5;
void work()
{phi[1]=1;for(ll i=2;i<=MX;++i){if(!p[i]){prime[++w]=i;phi[i]=i-1;}for(ll j=1;j<=w&&i*prime[j]<=MX;++j){p[i*prime[j]]=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);}}for(ll i=2;i<=n;++i)phi[i]+=phi[i-1];return;
}
int main()
{scanf("%lld%lld",&n,&m);work();for(ll l=1,r=0;l<=min(n,m);l=r+1){r=min(n/(n/l),m/(m/l));ans+=(phi[r]-phi[l-1])*(n/l)*(m/l);}printf("%lld",ans*2-n*m);return 0;
}