POJ

来源:互联网 发布:淘宝链接转化短链接 编辑:程序博客网 时间:2024/05/29 09:12
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 <= 10 6). 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
/*参考博客http://www.cnblogs.com/linyujun/p/5194170.htmlp为质数1. phi(p)=p-1,因为质数p除了1以外的因数只有p,故1至p的整数只有p与p不互质 2. 如果i mod p=0,那么phi(i*p)=phi(i)*p         3.若i mod p ≠0,那么phi(i*p)=phi(i)*( p-1 )   */#include <iostream>#include <cstring>const int N=1000007;typedef long long LL;LL phi[N];//欧拉打表LL prime[N];bool vis[N];using namespace std;void js()//线性筛法求欧拉{    int cnt=0;    memset(vis,true,sizeof(vis));    for(int i=2;i<N;i++)    {        if(vis[i])        {            prime[cnt++]=i;            phi[i]=i-1;//If i if prime,phi[i]=i-1;        }        for(int j=0;j<cnt&&i*prime[j]<N;j++)        {            LL k=i*prime[j];            vis[k]=false;            if(i%prime[j]==0)            {                phi[k]=phi[i]*prime[j];                break;            }            else            phi[k]=phi[i]*(prime[j]-1);        }    }}int main(){    int n;    js();    for(int i=2;i<=N;i++)        phi[i]+=phi[i-1];//打表    while(cin>>n&&n>0)    {        cout<<phi[n]<<endl;    }    return 0;}


原创粉丝点击