传送门
莫比乌斯反演,算是道模板题吧,但是比[POI2007]Zap难一些,zap我也有题解
对于这个题,一贯的套路,我们设
[f(d)=sum_{i=1}^{a}sum_{j=1}^{b}[gcd(i,j)==d]\
g(n)=sum_{n|d}f(d)=sum_{i=1}^{a}sum_{j=1}^{b}[n|gcd(i,j)]=lfloor frac{a}{n}
floorlfloor frac{b}{n}
floor
]
然后反演
[f(d)=sum_{d|n}mu(frac{n}{d})g(n)
]
然后考虑答案
[ans=sum_{din prime}sum_{d|n}mu(frac{n}{d})g(n)\
ans=sum_{din prime}sum_{d|n}mu(frac{n}{d})lfloor frac{a}{n}
floorlfloor frac{b}{n}
floor
]
设(T=frac{n}{d})
[ans=sum_{din prime}sum_{T=1}^{min(a,b)/d}mu(T)lfloor frac{a}{Td}
floorlfloor frac{b}{Td}
floor
]
再设(k=Td)
[ans=sum_{din prime}sum_{k=1}^{min(a,b)}mu(frac{k}{d})lfloor frac{a}{k}
floorlfloor frac{b}{k}
floor\
ans=sum_{k=1}^{min(a,b)}sum_{din prime}mu(lfloor frac{k}{d}
floor)lfloor frac{a}{k}
floorlfloor frac{b}{k}
floor\
ans=sum_{k=1}^{min(a,b)}sum_{din prime,d|k}mu(frac{k}{d})lfloor frac{a}{k}
floorlfloor frac{b}{k}
floor\
ans=sum_{k=1}^{min(a,b)}lfloor frac{a}{k}
floorlfloor frac{b}{k}
floor(sum_{din prime,d|k}mu(frac{k}{d}))\
]
然后后面可以线筛之后前缀和一下,剩下的数论分块就好了
代码:
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
void read(int &x) {
char ch; bool ok;
for(ok=0,ch=getchar(); !isdigit(ch); ch=getchar()) if(ch=='-') ok=1;
for(x=0; isdigit(ch); x=x*10+ch-'0',ch=getchar()); if(ok) x=-x;
}
#define rg register
const int maxn=1e7;
int T,n,m,pri[maxn/10],tot,mu[maxn+10],g[maxn+10];
bool vis[maxn+10];long long ans,sum[maxn+10];
void prepare()
{
mu[1]=1;
for(rg int i=2;i<=maxn;i++)
{
if(!vis[i])pri[++tot]=i,mu[i]=-1;
for(rg int j=1;j<=tot&&pri[j]*i<=maxn;j++)
{
vis[i*pri[j]]=1;
if(!(i%pri[j]))break;
else mu[i*pri[j]]=-mu[i];
}
}
for(rg int i=1;i<=tot;i++)
for(rg int j=1;j*pri[i]<=maxn;j++)g[j*pri[i]]+=mu[j];
for(rg int i=1;i<=maxn;i++)sum[i]=sum[i-1]+g[i];
}
int main()
{
read(T),prepare();
while(T--)
{
read(n),read(m);if(n>m)swap(n,m);ans=0;
for(rg int i=1,j;i<=n;i=j+1)
{
j=min(n/(n/i),m/(m/i));
long long t=1ll*(n/i)*(m/i)*(sum[j]-sum[i-1]);
ans+=t;
}
printf("%lld
",ans);
}
}