Poj3090 Visible Lattice Points(欧拉函数)

欧拉函数

欧拉函数的定义:1~N中与N互质的数的个数被称为欧拉函数,我们用phi[i]来记录与i互质的数的个数。

根据算数基本定理(唯一分解定理),即N可以分解成N=p1^c1*p2^c2*…pm^cm,其中pi为质数可以推出phi[N]=N * (p1 - 1) / p1 * (p2 - 1) / p2*…(pm - 1) / pm。

欧拉函数的部分性质:phi[n] = phi[n / p] * (n % (p ^ 2) ? p - 1 : p)(其中n % p == 0)。其他性质请自行百度……

下面来看一个例题,题目链接:http://poj.org/problem?id=3090

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

思路:易知在每条直线上只能看到一个点,由过原点的直线的斜率公式y/x知,能看到的点的坐标为横纵坐标互质的点。从而将问题转换为求欧拉函数,通过作图(经验)知,能看到的点关于y = x 对称,因而本题要求的就是结果为3 + 2 * phi[i](i:1~n),其中的3为(1,0),(0,1),(0,0)。在进行线性筛的同时利用上面说的欧拉函数的性质将每个数的欧拉函数求出来。
代码实现如下:
 1 #include <cstdio>
 2 #include <cstring>
 3 
 4 int c, n, m;
 5 int v[1007], p[1007];
 6 long long phi[1007], ans;
 7 
 8 void euler(int n) {
 9     memset(v, 0, sizeof(v));
10     m = 0;
11     for(int i = 2; i <= n; i++) {
12         if(v[i] == 0) {
13             v[i] = i;
14             p[m++] = i;
15             phi[i] = i - 1;
16         }
17         for(int j = 0; j < m; j++) {
18             if(p[j] > v[i] || p[j] > n / i) break;
19             v[i * p[j]] = p[j];
20             phi[i * p[j]] = phi[i] * (i % p[j] ? p[j] - 1 : p[j]);
21         }
22     }
23 }
24 
25 int main() {
26     scanf("%d", &c);
27     for(int icase = 1; icase <= c; icase++) {
28         scanf("%d", &n);
29         euler(n);
30         ans = 0;
31         for(int i =2; i <= n; i++) {
32             ans += phi[i];
33         }
34         printf("%d %d %lld\n", icase, n, ans * 2 + 3);
35     }
36 }

 

转载于:https://www.cnblogs.com/Dillonh/p/8868978.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值