数论基础 欧拉函数

版权声明:ACM代码随意转载。算法描述需备注来源。谢谢合作。 https://blog.csdn.net/Sensente/article/details/90081273

欧拉函数 Euler's totient function

例如φ(8)=4,因为1,3,5,7均和8互质。

N = P1 ^ q1 * P2 ^ q2 * … * Pn ^ qn//唯一分解定理
φ(N) = N * (1-1/P1) * (1-1/P2) * … * (1-1/Pn) //欧拉函数

例如:

8 = 2^3
ψ(8)=8×(1-1/2 ) =4;
10 = 1 × 2 × 5
ψ(10)=10×(1-1/2)×(1-1/5)=4;


代码:


#include <iostream>

#include <cstring>

#include <algorithm>

#include <stdlib.h>

//#define DEBUG

using namespace std;

typedef long long ll;

const ll MOD = 1000000007;

ll euler(ll n) { //欧拉公式

    ll ans = n;

    for(int i = 2;i * i<= n;i++) { //找因数

        if(n % i== 0) {          //若i为因数

            ans = ans / i * (i - 1);

            while(n % i == 0)    //去除因数 i 唯一分解

                n / = i;
        }
    }

    if(n>1) ans=ans/n*(n-1);//对于最后一个,同时也是最大的因数,可能会因为循环无法判断,特判。

    return ans;
}

int main() {

    ll n = 0;

    while(cin >> n) {

        if(n == 0) return 0;

        cout << eular(n) << endl;
    }

    return 0;
}

样题:

杭电1286  http://acm.hdu.edu.cn/showproblem.php?pid=1286

解析:https://blog.csdn.net/Sensente/article/details/90081579

杭电3501 http://acm.hdu.edu.cn/showproblem.php?pid=3501

解析:https://blog.csdn.net/Sensente/article/details/89505147

猜你喜欢

转载自blog.csdn.net/Sensente/article/details/90081273