POJ 2407.Relatives-欧拉函数O(sqrt(n))

Euler函数表达通式：euler(x)=x(1-1/p1)(1-1/p2)(1-1/p3)(1-1/p4)…(1-1/pn),或者φ(x)=x(1-1/p1)(1-1/p2)(1-1/p3)(1-1/p4)…..(1-1/pn),

euler(1)=1（唯一和1互质的数就是1本身）。

1.小于或等于n的数中，与n互质的数的总和为：φ(n) * n / 2  (n>1)。

2.n=d|nφ(d)，即n的因数（包括1和它自己）的欧拉函数之和等于n。

ll euler(ll n){
ll ans=n;
for(int i=2;i*i<=n;i++){                     //这里i*i只是为了减少运算次数，直接i<=n也没错，
if(n%i==0){                              //因为只有素因子才会加入公式运算。仔细想一下可以明白i*i的用意。
ans=ans/i*(i-1);
while(n%i==0)
n/=i;                            //去掉倍数
}
}
if(n>1)
ans=ans/n*(n-1);
return ans;
}

10的质因子为1，2，5；10的欧拉函数是1，3，7，9；i=2;2*2<10;10%2==0;ans=10/2*(2-1)=5;n=10/2=5;

i=3;3*3<10;10%3!=0跳出循环，执行下面的。此时n=5>1;ans=5/5*(5-1)=4;

POJ2407

 Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 14285 Accepted: 7133

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代码:
#include<cstdio>
#include<iostream>
using namespace std;
typedef long long ll;
ll euler(ll n){
ll ans=n;
for(int i=2;i*i<=n;i++){
if(n%i==0){
ans=ans/i*(i-1);
while(n%i==0)
n/=i;
}
}
if(n>1)
ans=ans/n*(n-1);
return ans;
}
int main(){
ll n;
while(~scanf("%lld",&n)){
if(n==0)break;
euler(n);
printf("%lld\n",euler(n));
}
return 0;
}


posted @ 2017-03-16 23:38  ZERO-  阅读(427)  评论(0编辑  收藏  举报