欧拉函数

 Relatives

 use MathJax to parse formulas

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

 首先讲一下欧拉函数    例如φ(8)=4,因为1,3,5,7均和8互质

计算方法  当n是素数时  答案为n-1  

 当n不是是素数时   

通式:φ(x)=x(1-1/p1)(1-1/p2)(1-1/p3)(1-1/p4)…..(1-1/pn)
其中p1, p2……pnx的所有质因数,x是不为0的整数

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <cstdlib>
using namespace std;
typedef long long ll ;
ll OL(ll n){ //返回euler(n)   
    int res=n,a=n;  
    for(ll i=2;i*i<=a;i++){//从小到大尝试n的质因数 
        if(a%i==0){//如果i是n的质因数 
            res=res/i*(i-1);//提了一个1/i出来,先进行除法是为了防止中间数据的溢出   
            while(a%i==0) a/=i;//欧拉函数只记算一种质因数 
        }  
    }  
    if(a>1) res=res/a*(a-1);//如果最后还剩因子 
    return res;  
}
int main()
{
    ll n;
    while(1)
    {
        cin>>n;
        if(n==0)
            break;
        ll ans=OL(n);
        cout<<ans<<endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/zcy19990813/p/9702700.html