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;
}

本文介绍了一种解决特定数学问题的方法:计算在一个由树木组成的m*n网格中,从起点(0,0)能看到多少棵树。当三棵树在同一直线上时,只能看到离观察者最近的一棵。通过算法计算互质数对的数量来得出最终答案。
653

被折叠的 条评论
为什么被折叠?



