BZOJ 2820: YY的GCD 莫比乌斯反演_数学推导_线性筛
Code:
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
#define maxn 10000009
const long long N = 10000009 ;
#define ll long long
#define setIO(s) freopen(s".in","r",stdin),freopen(s".out","w",stdout)
using namespace std;
int vis[maxn],prime[maxn],mu[maxn],g[maxn],tot;
long long sumv[maxn];
void init(){
mu[1]=1;
for(int i=2;i<maxn;++i) {
if(!vis[i]) { prime[++tot]=i,mu[i]=-1; }
for(int j=1;j<=tot && (ll)prime[j]*i < (ll)maxn;++j)
{
vis[prime[j]*i]=1;
if(i % prime[j]==0) {
mu[i * prime[j]]=0;
break;
}
mu[i * prime[j]]=-mu[i];
}
}
for(int i=1;i<=tot;++i)
for(ll j=1;(ll)j*prime[i]<N;++j)
g[prime[i]*j]+=mu[j];
for(int i=1;i<=10000000;++i) sumv[i] = (long long)sumv[i-1]+g[i];
}
ll work(int n,int m) {
if(n>m) swap(n,m);
long long ans=0;
for(ll i=1,j;i<=n;i=j+1) {
j = min(n/(n/i),m/(m/i));
ans += (n/i) * (m/i) * (sumv[j] - sumv[i-1]);
}
return ans;
}
int main(){
//setIO("input");
init();
int T,x,y; scanf("%d",&T);
while(T--) scanf("%d%d",&x,&y),printf("%lld\n",work(x,y));
return 0;
}