Visible Lattice Points
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 9734 Accepted: 5920
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
问题描述
有个n×n的网格,问从(0,0)处看,有多少个不被遮挡的点。
问题分析
从(0,0)处出发的直线,可记为y=kx。
k
=
y
0
−
0
x
0
−
0
=
y
0
x
0
k=\frac{y_0-0}{x_0-0}=\frac{y_0}{x_0}
k=x0−0y0−0=x0y0
那么不遮挡就是指y0与x0互质。显然如果y0和x0不互质,那么一定可以找到更小的正整数y0’和x0’使得它们的商为k,就会被挡住。由于要找的点的分布是关于y=x对称的,所以我们只看y>x部分的点。
画坐标轴,对于每个y=a,这条线上的点数正是欧拉函数φ(a)的值,因为欧拉函数φ(n)表示的就是比小于等于n的与n互质的数的个数。所以整个网格上不遮挡的点的个数显然就是把每条横轴上的点数(纵坐标对应的欧拉函数)相加,再乘2,再加1。
代码如下
#include<iostream>
using namespace std;
const int N=1005;
int phi[N+5];
int ans[N+5];
void phi_table(int n){
for(int i=2;i<=n;i++) phi[i]=0;
phi[1]=1;
for(int i=2;i<=n;i++){
if(phi[i]) continue;
for(int j=i;j<=n;j+=i){
if(!phi[j]) phi[j]=j;
phi[j]=phi[j]/i*(i-1);
}
}
}
void getans(int n){
ans[1]=3;
for(int i=2;i<=n;i++) ans[i]=ans[i-1]+2*phi[i];
}
int main(){
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
phi_table(N);
getans(N);
int c,t,i,n;
cin>>c;
for(t=1;t<=c;t++){
cin>>n;
cout<<t<<' '<<n<<' '<<ans[n]<<endl;
}
return 0;
}