poj 2478 Farey Sequence (歐拉函數)

  

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

題意:給定一個數n,求小於或等於n的數中兩兩互質組成的真分數的個數,其實就是求1到n中所有數的歐拉函數值的和,但是這並不需要每個數依次計算,劉汝佳的算法入門經典上有個類似篩法求素數的方法只有O(nloglogn)的複雜度。
代碼:
#include<stdio.h>
#include<string.h>
int phi[1000005];
__int64 ans[1000005];
int i,j,n;
void phi_table()
{
   for(i=2;i<=1000005;i++)
	  phi[i]=0;
   phi[1]=1;
   for(i=2;i<=1000005;i++)
	 if(!phi[i])
		for(j=i;j<=1000005;j+=i)
		{
		   if(!phi[j])
			   phi[j]=j;
		   phi[j]=phi[j]/i*(i-1);
		}
}

int main()
{   
    phi_table();
    ans[1]=0;
    for(i=2;i<=1000005;i++)
        ans[i]=ans[i-1]+phi[i];
    while(scanf("%d",&n),n)
    {   
        printf("%I64d\n",ans[n]);
    }
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章