1. 程式人生 > >POJ2478(SummerTrainingDay04-E 歐拉函數)

POJ2478(SummerTrainingDay04-E 歐拉函數)

else bool rational sam con out urn range log

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 <= 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
0

Sample Output

1
3
5
9

Source

POJ Contest,Author:[email protected] 求1-n的歐拉函數和即可。
 1 //2017-08-04
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <iostream>
 5 #include <algorithm>
 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 }

POJ2478(SummerTrainingDay04-E 歐拉函數)