POJ2407_Relatives【欧拉phi函数】【基本】

Relatives
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 11422 Accepted: 5571
Description




Given n, a positive integer, how many positive integers less than n are relatively prime to n? Two integers a and b are relatively prime if there are no integers x > 1, y > 0, z > 0 such 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
Source




Waterloo local 2002.07.01
题目大意:给你一个正整数N,求在小于N的范围内,有多少个正整数与N互质?
思路:典型的欧拉phi函数
欧拉函数(摘自百度百科):

在数论,对正整数n,欧拉函数φ(n)是少于或等于n的数中与n互质的数的数目。
φ(n) = n(1-1/p1)(1-1/p2)(1-1/p3)(1-1/p4)…..(1-1/pn),其中p1, p2……pn
为x的

质因数,x是不为0的整数。φ(1)=1(唯一和1互质的数(小于等于1)就是1本身)。

 (注意:每种质因数只一个。比如12=2*2*3那么φ(12)=12*(1-1/2)*(1-1/3)=4

一些定理:

1>若n是质数p的k次幂,φ(n) = p^k-p^(k-1) =(p-1)p^(k-1),因为除了p的倍数外,

其他数都跟n互质。

2>若n为素数,φ(n)  = n - 1;(同第6条)

3>当n为奇数时,φ(2n)=φ(n)

4>欧拉函数是积性函数——若m,n互质,φ(mn)=φ(m)φ(n)

5>欧拉定理:对任何两个互质的正整数a, m, m>=2有 a^φ(m) ≡ 1(mod m)

6>费马小定理:当m是质数p时,此式则为:a^(p-1)≡1(mod m)。


#include <stdio.h>
#include <math.h>

int Euler(int n)
{
    int i,ret = n;
    for(i = 2; i <= sqrt(1.0*n); i++)
    {
        if(n % i == 0)
        {
            ret = ret - ret/i;
        }
        while(n % i == 0)
            n /= i;
    }
    if(n > 1)
        ret = ret - ret/n;
    return ret;
}
int main()
{
    int p;
    while(~scanf("%d",&p) && p)
        printf("%d\n",Euler(p));
    return 0;
}


你可能感兴趣的:(POJ2407_Relatives【欧拉phi函数】【基本】)