Relatives

Relatives

Time Limit(Common/Java):1000MS/10000MS     Memory Limit:65536KByte
Total Submit: 9            Accepted: 4

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
分析:

用欧拉函数做。对于正整数n,欧拉函数可以求出在小于等于n的数中与n互质的数的个数。

欧拉函数:φ(x)=x(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本身)。 (注意:每种质因数只一个。比如12=2*2*3

那么φ(12)=12*(1-1/2)*(1-1/3)=4)

 

代码:
View Code
#include<stdio.h>
#include
<math.h>
int euler(long n)
{
long res=n, x=n;
long i,tmp=sqrt(n);
for (i=2; i<=tmp; i++)
{
if (x%i==0)
{
res
= res/i*(i-1);
}
while (x%i==0) x/=i; //去除x中所有的质因数i,确保下次计算时i是质因数。
}
if (x>1) res = res/x*(x-1); //当n是由两个质因数组成的时候,条件成立
return res;
}
int main()
{
long n;
while (scanf("%ld", &n), n)
{
printf(
"%ld\n", euler(n));
}
return 0;
}




posted on 2011-06-05 18:12  tzc_yujunyong  阅读(265)  评论(0)    收藏  举报