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, 0),(0, 1), (1, 1)
能看到的钉子满足gcd(x,y) = 1,2<=y<=n, 1<=x<y
答案就是计算
3
+
2
∗
∑
i
=
2
N
φ
(
i
)
3+2*\sum_{i = 2}^N\varphi(i)
3+2∗∑i=2Nφ(i)
欸氏筛法计算欧拉函数
#include <cstdio>
using namespace std;
const int maxn = 1005;
int T, n, cnt, phi[maxn];
int main()
{
scanf("%d", &T);
while (T--)
{
scanf("%d", &n);
for (int i = 2; i <= n; ++i) phi[i] = i;
for (int i = 2; i <= n; ++i)
if (phi[i] == i) //i是质数
for (int j = i; j <=n; j += i)
phi[j] = phi[j] / i * (i - 1);//j是合数,乘以质数(1-1/i)
int ans = 0;
for (int i = 2; i <= n; ++i)
ans += phi[i];
printf("%d %d %d\n", ++cnt, n, 3 + 2 * ans);
}
return 0;
}
线性筛法
看不太懂,先记住得了,数还是比较小,这题实际运行时间没有差别
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 1005;
int is_not_prime[maxn], prime[maxn], phi[maxn];
int T, n, tot, cnt, ans;
void euler()
{
//memset(is_not_prime, 0, sizeof(is_not_prime));
is_not_prime[1] = 1;
for (int i = 2; i <= n; ++i)
{
if (!is_not_prime[i])
{
prime[++tot] = i;
phi[i] = i - 1;
}
for (int j = 1; j <= tot && i * prime[j] < maxn; ++j)
{
is_not_prime[i * prime[j]] = 1;
phi[i * prime[j]] = phi[i] * (i % prime[j] ? prime[j] - 1 : prime[j]);
if (i % prime[j] == 0)
break;
}
}
}
int main()
{
scanf("%d", &T);
while (T--)
{
scanf("%d", &n);
tot = ans = 0;
euler();
for (int i = 2; i <= n; ++i)
ans += phi[i];
printf("%d %d %d\n", ++cnt, n, 3 + 2 * ans);
}
return 0;
}