Farey Sequence - POJ 2478 欧拉公式

来源:互联网 发布:河北工业大学知乎 编辑:程序博客网 时间:2024/05/28 11:50

Farey Sequence
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 11545 Accepted: 4488

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


        所谓欧拉公式就是对一个数j求有多少个比j小,且与j互斥的数(互斥即为最大公约数为1),比如4,这个数,满足该要求的为1、3两个数,8这个满足的为1、3、5、7四个数。欧拉公式的算法是对于一个数j,满足该要求的数的个数为——所有能够把它整除的素数k,d[j]=d[j]/k*(k-1)。比如8这个数只能被2这一素数整除,那么满足要求的个数为8/2*(2-1)=4个,再比如6,它可以被素数2和3整除,那么个数为6/2*(2-1)=3  再 3/3*(3-1)=2 共有两个数(1和5这两个数)。

        该题的题意是有多组测试数据,每组给你一个数n,问你从2-n这些数中每个数满足该要求的个数的和是多少。


下面是AC代码:

#include<cstdio>using namespace std;int p[1000005];       //p[j]表示小于j的正整数与j互斥的数有多少个,比如j=4,那么1/4,3/4共两个long long s[1000005]; //s[j]表示从p[2]加到p[j]一共有多少个数,因为没有试会不会超int,还是用long保险下吧int main(){ int i,j,n;  long long sum;  for (i=2;i<=1000000;i++)  //欧拉公式  { if(!p[i])               //如果这个数是素数    { for(j=i;j<=100000;j+=i) //所有能被这个数整除的数      { if(!p[j])            //没有涉及过的数先初始化一下p[j]的个数         p[j]=j;        p[j]=p[j]/i*(i-1);   //都除以i再乘以(i-1)      }    }  }  for(i=2;i<=1000002;i++)   s[i]=s[i-1]+p[i];  while(~scanf("%d",&n) && n)   printf("%lld\n",s[n]);}



0 0
原创粉丝点击