POJ 3090 Visible Lattice Points

A - Visible Lattice Points
Time Limit:1000MS    Memory Limit:65536KB    64bit IO Format:%I64d & %I64u
Submit Status

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, yN.

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)向外发出直线,遇到的第一个点会挡住后面的点,问这个点阵里一共能有多少个点。

分析:从斜率入手。

不管n是多少,斜率为0/n,n/0的两条上面始终只会有一个点,斜率为n/n的上也只会有一个点。

因为点阵关于y=x直线对称,所以只要算一半再乘二就好。

结合这些特殊的性质,答案便是,斜率为n/1到(n-1)/n的直线之间的点数*2+3.

重点在于如何求斜率为n/1到(n-1)/n的直线之间的点数。

观察可以得到,对于n×n,可以从0,0连接到(n,0)到(n,n)上,斜率将会是1/n,2/n......(n-1)/n;

可看做分式a/b的形式,如果a,b可以约分,说明前面已经计算过了这个斜率。就比如从(0,0)到(2,1)和从(0,0)到(4,2),(4,2)这个点次数被挡住,不计入总数。

问题变转化为求,不大于n,并且和n互质的数的个数。

欧拉函数。

做法:欧拉函数先打表,然后从i=3到i=n求欧拉函数,累加,就得到斜率为n/1到(n-1)/n的直线之间的点数,最后乘2加3,结束。

#include <stdio.h>
#define N 1005
int phi[N];
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])
            for(int j=i;j<=n;j+=i)
            {
                if(!phi[j])phi[j]=j;
                phi[j]=phi[j]/i*(i-1);
            }
}

int main()
{
        int t,n;
        scanf("%d",&t);
        phi_table(1000);
        int i=1;
        while(i<=t)
        {
                int sum=0;
                scanf("%d",&n);
                for(int i=2;i<=n;i++)
                        sum+=phi[i];
                printf("%d %d %d\n",i++,n,sum*2+3);
        }
        return 0;
}

PS:看到STATUS里有0MS,难道是把欧拉函数表直接写常数表。。。

你可能感兴趣的:(POJ 3090 Visible Lattice Points)