Visible Trees
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2902 Accepted Submission(s): 1266
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.
If two trees and Sherlock are in one line, Farmer Sherlock can only see the tree nearest to him.
Input
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)
Output
For each test case output one line represents the number of trees Farmer Sherlock can see.
Sample Input
2 1 1 2 3
Sample Output
1 5用容斥原理此题可以转化为求[1,m],[1,n]之间的互质数的个数,和GCD那道题不同的是(i,j)和(j,i)属于不同的组合,故不能用那种方法,可以枚举[1,m]中的每一个数,在[1,n]中有多少与之互质的数#include<stdio.h> #include<string.h> #include<math.h> #include<algorithm> using namespace std; int num; int p[15]; int o[100010]; void get(int n) { num=0; for(int i=2;i*i<=n;i++) { if(n%i==0) p[num++]=i; while(n%i==0) n/=i; } if(n>1) p[num++]=n; } int solve(int n) { int sum=0; for(int i=1;i<(1<<num);i++) { int s=0; int l=1; for(int j=0;j<num;j++) { if((i>>j)&1) { s++; l*=p[j]; } } if(s&1) sum+=n/l; else sum-=n/l; } return sum; } int main() { int t,n,m; long long sum; scanf("%d",&t); while(t--) { sum=0; scanf("%d%d",&m,&n); for(int i=1;i<=m;i++) { get(i); sum+=n-solve(n); } printf("%lld\n",sum); } return 0; }