• POJ2478 Farey Sequence


    Farey Sequence
    Time Limit: 1000MS   Memory Limit: 65536K
         

    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

    Source

    POJ Contest,Author:Mathematica@ZSU
     
    欧拉函数模板题,16ms的O(n)线性筛,代码是抄贾教的。。
    Codes:
     1 #include<cstdio>
     2 #include<iostream>
     3 using namespace std;
     4 int n,phi[1001000],tot,prime[500000];
     5 long long sum[1001000];
     6 bool check[1000100];
     7 void PHI(int n){
     8     phi[1] = 1;
     9     for(int i=2;i<=n;i++){
    10         if(!check[i]){
    11             prime[++tot] = i;
    12             phi[i] = i - 1;
    13         }
    14         for(int j=1;j<=tot;j++){
    15             if(prime[j]*i>n) break;
    16             check[prime[j]*i] = true;
    17             if(i%prime[j]==0){
    18                 phi[i*prime[j]] = phi[i] * prime[j];
    19                 break;
    20             }else   phi[i*prime[j]] = phi[i] * (prime[j]-1);
    21         }
    22     }
    23 }
    24 
    25 int main(){
    26     PHI(1000000);
    27     sum[2] = 1;
    28     for(int i=3;i<=1000000;i++) sum[i]+=sum[i-1] + phi[i];
    29     while(scanf("%d",&n)!=EOF && n) cout<<sum[n]<<endl;
    30     return 0;
    31 }
  • 相关阅读:
    详解实现Android中实现View滑动的几种方式
    一起写一个Android图片轮播控件
    Java核心技术点之多线程
    深入了解整数在计算机内部的表示
    Java核心技术点之接口
    Java核心技术点之内部类
    配置resin web方式部署项目
    rsa加密算法,前后端实现。
    引用百度bcebos jar 503问题
    HashMap get()返回值问题
  • 原文地址:https://www.cnblogs.com/zjdx1998/p/3866501.html
Copyright © 2020-2023  润新知