POJ 2478 Farey Sequence


Description

The Farey Sequence Fn for any integer n with n >= 2 is the set of irreducible rational numbers a/b with 0 < a < b <= n and gcd(a,b) = 1 arranged in increasing order. The first few are
F2 = {1/2}
F3 = {1/3, 1/2, 2/3}
F4 = {1/4, 1/3, 1/2, 2/3, 3/4}
F5 = {1/5, 1/4, 1/3, 2/5, 1/2, 3/5, 2/3, 3/4, 4/5}

You task is to calculate the number of terms in the Farey sequence Fn.

Input

There are several test cases. Each test case has only one line, which contains a positive integer n (2 <= n <= 106). There are no blank lines between cases. A line with a single 0 terminates the input.

Output

For each test case, you should output one line, which contains N(n) ---- the number of terms in the Farey sequence Fn.

Sample Input

2
3
4
5
0

Sample Output

1
3
5
9


欧拉函数的应用

很简单的一道题,但是直接使用欧拉函数会TLE
 1 #include<stdio.h>
 2 #include<math.h>
 3 #define N 1000010
 4 
 5 //欧拉函数 <模板>
 6 int euler_phi(int n)
 7 {
 8     int m = (int)sqrt(n+0.5);
 9     int ans = n;
10     for(int i = 2; i <= m; i++)
11         if(n % i == 0){//找素因子
12             ans = ans/i*(i-1);
13             while(n % i == 0)
14                 n /= i;//除尽
15         }
16     if(n>1)
17         ans = ans/n*(n-1);
18     return ans;
19 }
20 
21 int main()
22 {
23     int n;
24     while(scanf("%d", &n) && n != 0){
25         int sum = 0;
26         for (int i = 2; i <= n; i ++)
27             sum += euler_phi(i);
28         printf("%d\n", sum);
29     }
30     return 0;
31 }

于是,我们需要进行一些改进,欧拉函数可以写成递归形式,类似于记忆化搜索,我们不需要每次都重复计算,也就是所谓的欧拉函数打表
其中需要注意的一点就是,当 n 的值比较大的时候, sum 会超出 int 的范围(当输入 n 的值为100000时就会发现输出为负值),所以要改成long long 类型或者 _int64 类型
 1 #include<math.h>
 2 #include<stdio.h>
 3 #include<string.h>
 4 #define maxn 1000010
 5 
 6 //欧拉函数打表 <模板>
 7 int phi[maxn];
 8 void phi_table(int n)
 9 {
10     for(int i = 2; i <= n; i++)
11         phi[i] = 0;
12     phi[1] = 1;
13     for(int i = 2; i <= n; i++)
14         if(!phi[i])
15             for(int j = i; j <= n; j += i){
16                 if(!phi[j])
17                     phi[j] = j;
18                 phi[j] = phi[j]/i*(i-1);
19             }
20 }
21 
22 
23 int main()
24 {
25     memset(phi, 0, sizeof(phi));
26     phi_table(maxn);
27     int n;
28     while(scanf("%d", &n) && n != 0){
29         long long sum = 0;
30         for(int i = 2; i <= n; i++)
31             sum += phi[i];
32         printf("%lld\n", sum);
33     }
34     return 0;
35 }



优质内容筛选与推荐>>
1、python 正则表达式
2、杂化泛函计算时并行参数的设置与测试(1)
3、SQL SERVER存储过程一
4、js数据类型
5、《深入理解Bootstrap》读书笔记(二)


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn