欧拉函数

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

 1 #include <cstdio>
 2 #include <cmath>
 3 int Euler(int n)
 4 {
 5     int ret=n;
 6     for (int i=2;i<=sqrt(n);i++)
 7         if (n%i==0) {
 8             ret=ret/i*(i-1);
 9             while (n%i==0)
10             n/=i;    
11         } 
12     if (n>1) {
13             ret=ret/n*(n-1);
14         }
15     return ret;
16 }
17 int main()
18 {
19     int n;
20     while (~scanf("%d",&n)&&n) {
21         printf("%d\n",Euler(n));
22     }
23     return 0;
24 }    


这题就是欧拉函数的模板题,只要把欧拉函数写出来,就能够ACCEPT。鉴于各位大牛不屑于给新手普及数论基础,网上数论入门的题目解析真的很少,我就来写一写吧。
首先是循环条件i*i<=n;因为你可以想见,一个数的 平方根 再乘以 一个数的平方根加一 这是多少,这要比原数大。所以它的质因子里面不可能有比它的平方根还要大的数了。
ret为什么等于ret/n×(ret-1),因为这是k×(1-1/p)的另一种形式,这本来就是算欧拉函数值的式子,接下来,你把这个质因子除尽,然后去判断其他的质因子。
欧拉函数值计算的是某数从一到它本身的质因子个数,所以要除尽它的质因子。
如果除完之后还大于一,这个数依旧是它的质因子,然后继续执行欧拉函数的操作。完了。
posted @ 2018-08-09 20:37  xyee  阅读(112)  评论(0编辑  收藏  举报