SPOJ4491 Primes in GCD Table 莫比乌斯反演+分块+前缀和

来源:互联网 发布:2015房价知乎 编辑:程序博客网 时间:2024/05/24 05:02
Description
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 < 10^7.

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

题意就是求:1<=i<=a,1<=j<=b, gcd(i,j) 为一素数p的对数,可以考虑用莫比乌斯反演去做,关键是其中一个g(x)的求法,

可以在筛法中求解,最后用分块和前缀和进行优化。



#include <iostream>#include <cstdio>#include <map>#include <cmath>#include <algorithm>#include <cstring>#include <string>using namespace std;#define LL long long#define maxn 10000010bool v[maxn];int prime[maxn],mu[maxn],g[maxn],sum[maxn];void Moblus(){    memset(v,false,sizeof(v));    mu[1]=1;    g[1]=0;    sum[0]=sum[1]=0;    int tot=0;    for(int i=2;i<=maxn;i++)    {        if(!v[i]){            prime[tot++]=i;            mu[i]=-1;            g[i]=1;        }        for(int j=0;j<tot;j++){            if(i*prime[j]>maxn) break;            v[i*prime[j]]=true;            if(i%prime[j]==0){                mu[i*prime[j]]=0;                g[i*prime[j]]=mu[i];                break;            }else{                mu[i*prime[j]]=-mu[i];                g[i*prime[j]]=mu[i]-g[i];            }        }        sum[i]=sum[i-1]+g[i];    }}int main(){    int a,b,t;    Moblus();    scanf("%d",&t);    while(t--){        scanf("%d%d",&a,&b);        LL ans=0;        int n=min(a,b);        for(int i=1,last;i<=n;i=last+1){            last=min(a/(a/i),b/(b/i));            ans+=(LL)(a/i)*(b/i)*(sum[last]-sum[i-1]);        }        printf("%lld\n",ans);    }    return 0;}


0 0
原创粉丝点击