求区间x∈[1,n],y∈[1,m],gcd(x,y)=1的数量 [容斥]

Problem Description

There are many trees forming a m * n grid, the grid starts from (1,1). Farmer Sherlock is standing at (0,0) point. He wonders how many trees he can see.

If two trees and Sherlock are in one line, Farmer Sherlock can only see the tree nearest to him.

Input Output
The first line contains one integer t, represents the number of test cases. Then there are multiple test cases. For each test case there is one line containing two integers m and n(1 ≤ m, n ≤ 100000) For each test case output one line represents the number of trees Farmer Sherlock can see.

样例

Sample Input Sample Output
2
1 1 1
2 3 5

解题报告

设:

G(N)=[1,m]N

该问题就是求:

i=1nG(N)

代码如下:

//求区间x[1,n],y[1,m],gcd(x,y)==1的数量
#include
#define MAX_C 32
typedef long long LL;
int cs[MAX_C],u;

int slove(int m,int n){
    u=0;
    for(int i=2;i*i<=n;i++)
        if(n%i==0){
            cs[u++]=i;
            while(n%i==0) n/=i;
        }
    if(n>1) cs[u++]=n;

    int ans=0;
    for(int i=1;i<(1<int cnt=0,res=1;
        for(int k=0;kif(i>>k&1){
                res*=cs[k];
                cnt++;
            }
        ans+=cnt&1?m/res:-m/res;
    }
    return m-ans;
}

int main()
{
    int T,a,b;
    scanf("%d",&T);
    while(T--){
        scanf("%d%d",&a,&b);
        LL ans=0; //一组不超int 但是1e5组可能超
        for(int i=1;i<=a;i++)
            ans+=slove(b,i);
        printf("%lld\n",ans);
    }
    return 0;
}

你可能感兴趣的:(容斥原理,数学知识点)