GYM101982B Coprime Integers(莫比乌斯反演)
题意
给出两个区间[a, b]和[c, d],x必须属于第一个区间,y必须属于第二个区间,x和y互质才算进答案,询问x y总对数。
题解
板子
#include<bits/stdc++.h> using namespace std; const int maxn=1e7+100; typedef long long ll; bool check[maxn]; ll prime[maxn]; ll mu[maxn]; void mb () { memset(check,0,sizeof(check)); mu[1]=1; int tot=0; for (int i=2;i<maxn;i++) { if (!check[i]) { prime[tot++]=i; mu[i]=-1; } for (int j=0;j<tot;j++) { if (i*prime[j]>=maxn) break; check[i*prime[j]]=true; if (i%prime[j]==0) { mu[i*prime[j]]=0; break; } else { mu[i*prime[j]]=-mu[i]; } } } } ll sum[maxn]; ll solve (int n,int m) { ll ans=0; if (n>m) swap(n,m); for (int i=1,la=0;i<=n;i=la+1) { la=min(n/(n/i),m/(m/i)); ans+=(ll)(sum[la]-sum[i-1])*(n/i)*(m/i); } return ans; } int main () { mb(); sum[0]=0; for (int i=1;i<maxn;i++) sum[i]=sum[i-1]+mu[i]; int a,b,c,d; scanf("%d%d%d%d",&a,&b,&c,&d); ll ans=solve(b,d)-solve(a-1,d)-solve(b,c-1)+solve((a-1),c-1); printf("%lld\n",ans); }