Visible Lattice Points(POJ-3090)

Problem 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

————————————————————————————————————————————————————

题意:从原点看第一象限的所有点,求能直接看到的点的数目

思路:

题目要求的是从原点能看到的点的个数。

只有 1*1的时候,3个点,根据图明显的可以看出,只要计算下三角,即:结果=下三角的个数*2+斜率为1的点

因此,我们只需计算斜率 k\in(0,1) 的个数即可

1*1 时,有:0,共 1 个

2*2 时,有:0、1/2,共 2 个,添加 1 个

3*3 时,有:0、1/2、1/3、2/3,共 4 个,添加 3 个

4*4 时,有:0、1/2、1/3、2/3/、1/4、2/4、3/4,去重 1 个后,共 6 个,添加 2 个

5*5 时,有:0、1/2、1/3、2/3、1/4、3/4、1/5、2/5、3/5、4/5,共 10 个,添加 4 个

由上可发现一规律:对于 n*n,可从 (0, 0) 连接到 (n,0) 至 (n,n) 上,斜率是:1/n、2/n、3/n、...、(n-1)/n

凡是分子、分母能约分的,即有公约数的,前面都已经有过了,所以每次添加的个数就是分子和分母互质的个数,因此问题也就转换为:对一个数 n,求小于 n 的与 n 互质的数的个数并乘以2再加一,也就是求欧拉函数再乘2加1

Source Program

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<string>
#include<cstdlib>
#include<queue>
#include<set>
#include<map>
#include<stack>
#include<ctime>
#include<vector>
#define INF 0x3f3f3f3f
#define PI acos(-1.0)
#define N 10001
#define MOD 123
#define E 1e-6
using namespace std;
int phi[N];
void Euler()
{
    for(int i=1;i<=N;i++)
        phi[i]=i;

    for(int i=2;i<=N;i+= 2)
        phi[i]/=2;

    for(int i=3;i<=N;i+= 2)
    {
        if(phi[i]==i)
        {
            for(int j=i;j<=N;j+=i)
                phi[j]=phi[j]/i*(i-1);
        }
    }
}
int main()
{
    Euler();
    int t;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        int sum=0;
        for(int i=1;i<=n;i++)
            sum+=phi[i];
        cout<<sum*2+1<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/u011815404/article/details/81347503
今日推荐