Farey Sequence
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 16927 | Accepted: 6764 |
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 <= 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
Source
,Author:Mathematica@ZSU
求1-n的欧拉函数和即可。
1 //2017-08-04 2 #include3 #include 4 #include 5 #include 6 7 using namespace std; 8 9 const int N = 1000010;10 int phi[N],prime[N],tot;11 long long ans[N];12 bool book[N];13 14 void getphi()//线性欧拉函数筛15 { 16 int i,j; 17 phi[1]=1; 18 for(i=2;i<=N;i++)//相当于分解质因式的逆过程 19 { 20 if(!book[i])21 { 22 prime[++tot]=i;//筛素数的时候首先会判断i是否是素数。 23 phi[i]=i-1;//当 i 是素数时 phi[i]=i-1 24 } 25 for(j=1;j<=tot;j++) 26 { 27 if(i*prime[j]>N) break; 28 book[i*prime[j]]=1;//确定i*prime[j]不是素数 29 if(i%prime[j]==0)//接着我们会看prime[j]是否是i的约数 30 { 31 phi[i*prime[j]]=phi[i]*prime[j];break; 32 } 33 else phi[i*prime[j]]=phi[i]*(prime[j]-1);//其实这里prime[j]-1就是phi[prime[j]],利用了欧拉函数的积性 34 } 35 } 36 }37 38 int main()39 { 40 int n; 41 getphi();42 ans[2] = 1;43 for(int i = 3; i < N; i++){44 ans[i] = ans[i-1]+phi[i];45 }46 while(scanf("%d", &n) && n){47 printf("%lld\n", ans[n]);48 }49 50 return 0;51 }