spoj Primes in GCD Table 莫比乌斯反演

57 篇文章 0 订阅

Johnny has created a table which encodes the results of some operation -- a function of two arguments. But instead of a boring multiplication table of the sort you learn by heart at prep-school, he has created a GCD (greatest common divisor) table! So he now has a table (of height a and width b), indexed from (1,1) to (a,b), and with the value of field (i,j) equal to gcd(i,j). He wants to know how many times he has used prime numbers when writing the table.

Input

First, t ≤ 10, the number of test cases. Each test case consists of two integers, 1 ≤ a,b < 107.

Output

For each test case write one number - the number of prime numbers Johnny wrote in that test case.

Example

Input:
2
10 10
100 100

Output:
30
2791



莫比乌斯的理解见  传送门

题意:

要求求出gcd(x , y)为质数的个数,x ,y的区间见题

题解:

                  令        f(p)=gcd(x,y)为p       (p为质数)

                     F(pk)=gcd(x,y)>=p   (k为质数)


公式借鉴    传送门

ans=pmin(n,m)f(p)=pmin(n,m)k=1min(n,m)μ(k)F(pk)=pmin(n,m)k=1min(n,m)μ(k)npkmpk

直接这样做会TLE,那么考虑优化,令t=pk

ans=t=1min(m,n)p|tntmtμ(tp)

我们便可以将 a[t]=p|tμ(tp) 预处理出来,再对其求前缀和,然后对其分块求解



#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;

#define MAXN 10000000
#define LL long long
bool check[MAXN+10];
int primer[MAXN+10];
int mu[MAXN+10];
int sum[MAXN+10];

void Moblus()
{
    memset(check,0,sizeof(check));
    mu[1]=1;
    int tot=0;
    for(int i=2;i<=MAXN;i++){
        if(!check[i]){
            primer[tot++]=i;
            mu[i]=-1;
        }
        for(int j=0;j<tot&&i*primer[j]<=MAXN;j++){
            check[i*primer[j]]=true;
            if(i%primer[j]==0){
                mu[i*primer[j]]=0;
                break;
            }
            mu[i*primer[j]]=-mu[i];
        }
    }

    ///
    sum[0]=0;
    for(int i=0;i<tot;i++)
        for(int j=primer[i];j<MAXN;j+=primer[i])
            sum[j]+=mu[j/primer[i]];

    for(int i=1;i<MAXN;i++)
        sum[i]+=sum[i-1];
}

LL solve(int n,int m)
{
    LL ans=0;
    if(n>m) swap(n,m);
    for(int i=1,last;i<=n;i=last+1){
        last=min(n/(n/i),m/(m/i));
        ans+=(LL)(sum[last]-sum[i-1])*(n/i)*(m/i);
    }
    return ans;
}

int main()
{
    int T;
    Moblus();
    int a,b;
    freopen("in.txt","r",stdin);
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&a,&b);
        LL ans=solve(a,b);
        printf("%lld\n",ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值