Visible Lattice Points
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.
![](https://www.bnuoj.com/v3/images/3090_1.png)
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
这是我一开始用的笨办法。。果断超时了。。。
#include <stdio.h>
#include <string.h>
int vis[1100][1100];
int gcd(int a, int b)
{
if(b == 0){
return a;
}
return gcd(b, a % b);
}
int main()
{
memset(vis, 0, sizeof(vis));
int C;
scanf("%d", &C);
for(int c = 1; c <= C; c++ ){
int n, ans = 0;
scanf("%d", &n);
for(int i = 2; i <= n; i++ )
for(int j = 1; j <= i - 1; j++ ){
if(vis[i][j])
continue;
else if(gcd(i, j) == 1){
for(int k = 2; k * i <= 1005 && k * j <= 1005; k++ )
vis[k*i][k*j] = 1;
ans++;
}
}
ans = ans * 2 + 3;
printf("%d %d %d\n", c, n, ans);
}
return 0;
}
后来才知道有欧拉方程这种东西,先来看一下欧拉方程:
在数论,对正整数n,欧拉函数是小于等于n的数中与n互质的数的数目。此函数以其首名研究者欧拉命名(Euler'so totient function),它又称为Euler's totient function、fai函数、欧拉商数等。 例如φ(8)=4,因为1,3,5,7均和8互质。 从欧拉函数引伸出来在环论方面的事实和拉格朗日函数构成了欧拉定理的证明。
模板直接看下面的代码。
还有这道题可以有一个递推关系。假设当前的size为N,各个size的线段总数为sum[],那么递推关系为sum[N] = sum[N-1] +2 * Euler[N]。因为(x,y)要互质,而当size为N时新增的点的坐标只有(0~N,N)和(N,0~N),所以问题转化为求小于等于N的数中与N互质的数的数目,这个数目乘上2,加上上一个阶段的数目。
#include <cstdio>
int s[1001];
//欧拉公式模板
int Euler(int tot)
{
int num=tot;
for(int i=2; i<=tot; i++){
if(tot%i==0)
num=num/i*(i-1);
while(tot%i==0)
tot/=i;
}
return num;
}
int solve(int n)
{
int sum = 0;
if(n == 1)
return 3;
sum = solve(n - 1);
sum += 2 * Euler(n);
return sum;
}
int main()
{
int c;
scanf("%d", &c);
for(int i = 1; i <= c; i++){
int n;
scanf("%d", &n);
printf("%d %d %d\n", i, n, solve(n));
}
return 0;
}