poj 2478 Farey Sequence

来源:互联网 发布:nba2k15捏樱木花道数据 编辑:程序博客网 时间:2024/06/08 00:09
Farey Sequence
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 12259 Accepted: 4752

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

23450

Sample Output

1359

Source

POJ Contest,Author:Mathematica@ZSU


题目大意:
      给你一个数n,让你求从2到n为分母中的最简真分数的个数是多少个?

题解:
      就相当于求一个数m(2<=m<=n),求1到m中和m互质的个数。
      然后套用欧拉公式。

#include<stdio.h>#include<string.h>const int N=1000000;int a[N+5];void Init_oula()//预处理求出1到1000000的欧拉函数的值{    int i,j;    memset ( a, 0 ,sizeof (a)) ;    for ( i = 2 ; i <= N ; i ++ )    {//筛选求a        if ( ! a[i] )        {            for ( j = i ; j <= N ; j += i )            {                if ( ! a[j] )                    a[j ] = j ;                a[j] = a[j] / i * ( i - 1 ) ;            }        }    }}int main(){    Init_oula();    int i,n;    long long sum;    while (scanf("%d",&n))    {        if(n==0)        {            break;        }        sum = 0 ;        for ( i = 2 ; i <= n ; i ++ )        {            //printf("%d\n",a[i]);            sum += a[i] ;        }        printf("%I64d\n",sum);    }    return 0;}




0 0