POJ 2478 Farey Sequence

Problem 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
 
Sample Output
1
3
5
9
Fi中含分母i的项数为fi。由于每项的分子与分母互质,因此与i互质的整数的个数即为fi。显然,fi等于欧拉函数f(i)的值。
代码如下:
#include<stdio.h>
#include<math.h>
#include<string.h>
int s[32767],num=1;
bool u[32767];
void preper()
{
    int i,j;
    memset(u,true,sizeof(u));
    for(i=2;i<=32767;i++)
    {
        if(u[i]) s[num++]=i;
        for(j=1;j<num;j++)
        {
            if(i*s[j]>32767) break;
            u[i*s[j]]=false;
            if(i%s[j]==0) break;
        }
    }
}
int main()
{
    int i,a,b,sum=1,count=0;
    char c;
    preper();
    while(1)
    {
        scanf("%d",&a);
        if(a==0) break;
        scanf("%d",&b);
        sum*=floor(pow(a,b)+0.5);
        c=getchar();
        if(c=='
')
        {
            sum-=1;
            for(i=num-1;i>=1;i--)
            {
                if(sum%s[i]==0)
                {
                    count=0;
                    while(sum%s[i]==0)
                    {
                        count++;
                        sum/=s[i];
                    }
                if(sum!=1)    printf("%d %d ",s[i],count);
                else {printf("%d %d
",s[i],count); break;}
                }
            }
            sum=1;
        }
    }
    return 0;
}
 
原文地址:https://www.cnblogs.com/duan-to-success/p/3528879.html