欧拉函数计算(模板)

对于正整数n,欧拉函数phi(n)表示的是所有小于等于n的正整数中与n互素的数的个数
phi(x) = x(1-1/p1)(1-1/p2)(1-1/p3)(1-1/p4)…(1-1/pn),其中p1,p2……pn为x的所有素因数,x是不为0的整数,phi(1)=1
结论 一个数的所有质因子之和是phi(n)*n/2

//直接计算欧拉phi函数,phi(n)为不超过n且与n互素的正整数的个数
int euler_phi(int n) {
    int m = (int)sqrt(n + 0.5);
    int ans = n;
    for (int i = 2; i <= m; ++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;
}
//筛选法计算欧拉函数phi(1),phi(2)...phi(n)
const int maxn = 1050;
int phi[maxn];
void phi_table(int n) {
    for (int i = 2; i <= n; ++i) phi[i] = 0;
    phi[1] = 1;
    for (int i = 2; i <= n; ++i) {
        if (0 == phi[i]) {
            for (int j = i; j <= n; j += i) {
                if (0 == phi[j]) phi[j] = j;
                phi[j] = phi[j] / i * (i - 1);
            }
        }
    }
}
posted @ 2018-02-25 10:56  不想吃WA的咸鱼  阅读(1481)  评论(0编辑  收藏  举报