欧拉函数 POJ 2407 Relatives&&POJ 2478 Farey Sequence

ZQUOJ 22354&&&POJ 2407  Relatives

 

Description

Given n, a positive integer, how many positive integers less than n are relatively prime to? Two integers a and b are relatively prime if there are no integers x > 1, y > 0, z > 0such that a = xy and b = xz.

Input

There are several test cases. For each test case, standard input contains a line with n <= 1,000,000,000. A line containing 0 follows the last case.

Output

For each test case there should be single line of output answering the question posed above.

Sample Input

 

7

12

0

 

Sample Output

 

6

4

有关欧拉函数的知识请参考:http://blog.csdn.net/hillgong/article/details/4214327
题目分析:没什么好讲的,纯粹的欧拉函数模板。

AC代码:
View Code
 1 #include<stdio.h>

 2 int main()

 3 {

 4     int i,n,rea;

 5     while(scanf("%d",&n)&&n)

 6     {

 7         rea=n;

 8         for(i=2;i*i<=n;i++)

 9             if(n%i==0)

10             {

11                 rea=rea-rea/i;

12                 do{

13                     n/=i;

14                 }while(n%i==0);

15             }

16         if(n>1)

17             rea=rea-rea/n;

18         printf("%d\n",rea);

19     }

20     return 0;

21 }

 

 

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

2

3

4

5

0

Sample Output

1

3

5

9

题意:求2到n的连续欧拉函数的值的和。
分析:因为要频繁地用欧拉函数的值,所以需要预先打表。下面介绍递推求欧拉函数的方法。
可预先置所有数的欧拉函数值为它本身,若p是一个正整数且满足f(p)=p-1,那么p是素数,在遍历过程中如果遇到欧拉函数与自身相等的情况,那么说明该数是素数,把这个数的欧拉函数值改变,同时也把能被该素因子整除的数改变。时间复杂度度为O(nln n)。

AC代码:
View Code
 1 #include<stdio.h>

 2 #define MAXN 1000000

 3 double phi[MAXN+10];

 4 int main()

 5 {

 6     int i,j,n;

 7     for(i=1;i<=MAXN;i++)    //递推求欧拉函数

 8         phi[i]=i;

 9     for(i=2;i<=MAXN;i+=2)

10         phi[i]/=2;

11     for(i=3;i<=MAXN;i+=2)

12         if(phi[i]==i)

13         {

14             for(j=i;j<=MAXN;j+=i)

15                 phi[j]=phi[j]/i*(i-1);

16         }

17     for(i=3;i<=MAXN;i++)  //打表处理FN(2到n的欧拉函数值的和)

18         phi[i]+=phi[i-1];

19     while(scanf("%d",&n)&&n)

20         printf("%.f\n",phi[n]);

21     return 0;

22 }

你可能感兴趣的:(sequence)