[洛谷4450]双亲数
题目链接:https://www.luogu.org/problemnew/show/P4450
题目要求(之后令\(n<m\))
\[\sum\limits_{i=1}^n\sum\limits_{j=1}^m[gcd(i,j)==d]
\]
同时除上\(d\),有
\[\sum\limits_{i=1}^{\lfloor\frac{n}{d}\rfloor}\sum\limits_{j=1}^{\lfloor\frac{m}{d}\rfloor}[gcd(i,j)==1]
\]
然后发现最后面其实是莫比乌斯反演的形式,继续改写式子
\[\sum\limits_{i=1}^{\lfloor\frac{n}{d}\rfloor}\sum\limits_{j=1}^{\lfloor\frac{m}{d}\rfloor}\sum\limits_{x|i,x|j}\mu(x)
\]
然后我们把枚举改一下顺序,得到
\[\sum\limits_{x=1}^{\lfloor\frac{n}{d}\rfloor}\mu(x)\lfloor\dfrac{n}{dx}\rfloor\lfloor\dfrac{m}{dx}\rfloor
\]
然后我们只要线筛求出\(\mu\)函数之后就可以做这题了(当然可以使用整除分块)
/*program from Wolfycz*/
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define inf 0x7f7f7f7f
using namespace std;
typedef long long ll;
typedef unsigned int ui;
typedef unsigned long long ull;
inline char gc(){
static char buf[1000000],*p1=buf,*p2=buf;
return p1==p2&&(p2=(p1=buf)+fread(buf,1,1000000,stdin),p1==p2)?EOF:*p1++;
}
inline int frd(){
int x=0,f=1; char ch=gc();
for (;ch<'0'||ch>'9';ch=gc()) if (ch=='-') f=-1;
for (;ch>='0'&&ch<='9';ch=gc()) x=(x<<3)+(x<<1)+ch-'0';
return x*f;
}
inline int read(){
int x=0,f=1; char ch=getchar();
for (;ch<'0'||ch>'9';ch=getchar()) if (ch=='-') f=-1;
for (;ch>='0'&&ch<='9';ch=getchar()) x=(x<<3)+(x<<1)+ch-'0';
return x*f;
}
inline void print(int x){
if (x<0) putchar('-'),x=-x;
if (x>9) print(x/10);
putchar(x%10+'0');
}
const int N=1e6;
int prime[N+10],miu[N+10],sum[N+10];
bool inprime[N+10];
void prepare(){
miu[1]=sum[1]=1; int tot=0;
for (int i=2;i<=N;i++){
if (!inprime[i]) miu[prime[++tot]=i]=-1;
for (int j=1;j<=tot&&i*prime[j]<=N;j++){
inprime[i*prime[j]]=1;
if (i%prime[j]==0){
miu[i*prime[j]]=0;
break;
}miu[i*prime[j]]=-miu[i];
}
sum[i]=sum[i-1]+miu[i];
}
}
int main(){
prepare();
int n=read(),m=read(),d=read();
ll Ans=0; n/=d,m/=d;
if (n>m) swap(n,m);
for (int i=1,pos;i<=n;i=pos+1){
pos=min(n/(n/i),m/(m/i));
Ans+=1ll*(sum[pos]-sum[i-1])*(n/i)*(m/i);
}
printf("%lld\n",Ans);
return 0;
}