【题目】
Description
A lattice point (x, y) in the first quadrant (x and y are integers greater than or equal to 0), other than the origin, is visible from the origin if the line from (0, 0) to (x, y) does not pass through any other lattice point. For example, the point (4, 2) is not visible since the line from the origin passes through (2, 1). The figure below shows the points (x, y) with 0 ≤ x, y ≤ 5 with lines from the origin to the visible points.
Write a program which, given a value for the size, N, computes the number of visible points (x, y) with 0 ≤ x, y ≤ N.
Input
The first line of input contains a single integer C (1 ≤ C ≤ 1000) which is the number of datasets that follow. Each dataset consists of a single line of input containing a single integer N (1 ≤ N ≤ 1000), which is the size.
Output
For each dataset, there is to be one line of output consisting of: the dataset number starting at 1, a single space, the size, a single space and the number of visible points for that size.
Sample Input
4 2 4 5 231
Sample Output
1 2 5 2 4 13 3 5 21 4 231 32549
【分析】
首先我们要知道一个东西,就是点 会挡住后面所有的
(g 是大于 1 的整数)
也就是说,如果一个点会被挡住,那么它的 x,y 就必然有一个大于 1 的公因数
那么对于所有的点 ,如果 x 和 y 互质,那么它就可以被看见
现在对于这道题来说,直接枚举 x 和 y 的话显然会超时,我们可以只枚举 x,然后找与 x 互质的 y 的个数,于是我们想到欧拉函数,欧拉函数 phi(n) 就表示 1~n 中与 n 互质的数的个数,所以我们先预处理筛出欧拉函数,直接统计答案即可
最终答案:
其中 3 代表了(1,1),(0,1),(1,0)这三个点
还是简单说一下线性筛欧拉函数,这个东西主要是运用了欧拉函数的三个性质:
- 如果 i 是质数,那么 phi[ i ] = i - 1;
- 如果 a mod b == 0 并且 b 是质数,那么 phi[ a * b ] = phi[ a ] * b
- 如果 a mod b != 0 并且 b 是质数(也就是说a,b互质),那么 phi[ a * b ] = phi[ a ] * phi[ b ]
根据这三个性质筛就可以了
【代码】
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 1005
using namespace std;
int phi[N],prime[N];
bool mark[N];
void init()
{
int i,j,sum=0;
memset(mark,true,sizeof(mark));
mark[0]=mark[1]=false;
for(i=2;i<N;++i)
{
if(mark[i]) prime[++sum]=i,phi[i]=i-1;
for(j=1;j<=sum&&i*prime[j]<N;++j)
{
mark[i*prime[j]]=false;
if(i%prime[j]==0)
{
phi[i*prime[j]]=phi[i]*prime[j];
break;
}
else phi[i*prime[j]]=phi[i]*(prime[j]-1);
}
}
}
int main()
{
int n,i,j,x,ans;
scanf("%d",&n);
init();
for(i=1;i<=n;++i)
{
ans=3;
scanf("%d",&x);
for(j=1;j<=x;++j)
ans+=2*phi[j];
printf("%d %d %d\n",i,x,ans);
}
return 0;
}