代码改变世界

YY的GCD

2019-05-06 20:50  一只弱鸡丶  阅读(131)  评论(0编辑  收藏  举报

传送门:

 

#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <string>
using namespace std;
#define ll long long
#define re register
const int N=1e7+10;
const int M=1e7;
void read(int &a)
{
    a=0;
    int d=1;
    char ch;
    while(ch=getchar(),!isdigit(ch))
        if(ch=='-')
            d=-1;
    a=ch^48;
    while(ch=getchar(),isdigit(ch))
        a=(a<<3)+(a<<1)+(ch^48);
    a*=d;
}
int mu[N],pri[N],cnt;
bool vis[N];
ll sum[N];
inline void init()
{
    mu[1]=1;
    for(re int i=2;i<=M;i++)
    {
        if(!vis[i])
            mu[i]=-1,pri[++cnt]=i;
        for(re int j=1;j<=cnt&&i*pri[j]<=M;j++)
        {
            vis[i*pri[j]]=1;
            if(i%pri[j]==0)
                break;
            mu[i*pri[j]]=-mu[i];
        }
    }
    for(re int j=1;j<=cnt;j++)
        for(re int i=1;i*pri[j]<=M;i++)
            sum[i*pri[j]]+=mu[i];
    for(re int i=1;i<=M;i++)
        sum[i]+=sum[i-1];
}
int main()
{
    init();
    int T;
    read(T);
    while(T--)
    {
        int n,m;
        read(n);
        read(m);
        if(n>m)
            swap(n,m);
        ll ans=0;
        for(re int l=1,r;l<=n;l=r+1)
        {
            r=min(n/(n/l),m/(m/l));
            ans+=(sum[r]-sum[l-1])*(n/l)*(m/l);
        }
        printf("%lld\n",ans);
    }
    return 0;
}