POJ 3090 ZOJ 2777 UVALive 3571 Visible Lattice Points(用递推比用欧拉函数更好)

来源:互联网 发布:catia v5软件下载 编辑:程序博客网 时间:2024/05/19 03:17

题目:

Description

A lattice point (xy) 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 (xy) 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 (xy) with 0 ≤ xy ≤ 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 (xy) with 0 ≤ xy ≤ 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

4245231

Sample Output

1 2 52 4 133 5 214 231 32549

这个题目当然可以用欧拉函数来做,不过我更喜欢这个递推的方法。

代码:

#include<iostream>#include<stdio.h>using namespace std;int r[1001];int main(){r[1] = 1;for (int i = 2; i <= 1000; i++){r[i] = i*i;for (int j = 2; j <= i; j++)r[i] -= r[i / j];}int t, n;cin >> t;for (int cas = 1; cas <= t; cas++){cin >> n;cout << cas << " " << n << " " << r[n] + 2 << endl;}return 0;}
代码很简洁而且非常高效,16ms AC

这个递推式是什么原理呢?

首先解释一下,这个r不是答案,r+2才是答案,也就是说,

我没有计算x=0或者y=0的情况,也就是没有计算(0,1)和(1,0)这2个点。

然后怎么算r呢?

枚举gcd(x,y)

gcd(x,y)=1的情况有r[n]种,gcd(x,y)=2的情况有r[n/2]种

gcd(x,y)=3的情况有r[n/3]种......

所有的加起来,一共是n*n,这就得到了递推式。

2 0
原创粉丝点击