1. 程式人生 > >求區間x∈[1,n],y∈[1,m],gcd(x,y)=1的數量 [容斥]

求區間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<stdio.h>
#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<<u);i++){ int cnt=0,res=1; for
(int k=0;k<u;k++) if(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; }