其他分享
首页 > 其他分享> > [AcWing 874] 筛法求欧拉函数

[AcWing 874] 筛法求欧拉函数

作者:互联网

image

复杂度 $ O(n) $

总体复杂度 $ 10^{6} $


点击查看代码
#include<iostream>

using namespace std;
const int N = 1e6 + 10;
typedef long long LL;
int primes[N], cnt;
int eulers[N];
bool st[N];

void get_eulers(int n)
{
    eulers[1] = 1;
    for (int i = 2; i <= n; i ++) {
        if (!st[i]) {
            primes[cnt ++] = i;
            eulers[i] = i - 1;
        }
        for (int j = 0; primes[j] <= n / i; j ++) {
            st[primes[j] * i] = true;
            if (i % primes[j] == 0) {
                eulers[primes[j] * i] = eulers[i] * primes[j];
                break;
            }
            eulers[primes[j] * i] = eulers[i] * (primes[j] - 1);
        }

    }
}
int main()
{
    int n;
    cin >> n;
    get_eulers(n);
    LL res = 0;
    for (int i = 1; i <= n; i ++)   res += eulers[i];
    cout << res << endl;
    return 0;
}

  1. 记 $ primes[j] $ 为 $ P_j $,分以下三种情况求欧拉函数:
    ① $ i $ 是质数,$ 1 $ ~ $ i - 1 $ 每个数都与 $ i $ 互质,$ \phi(i) = i - 1 $;
    ② $ P_j $ 是 $ i $ 的质因子,由于 $ i = P_1^{\alpha_1} \times P_2^{\alpha_2} \times \cdots \times P_k^{\alpha_k} $ ,$ P_j $ 必是 $ P_1 $ ~ $ P_k $ 其中的一项,那么 $ P_j \times i = P_1^{\alpha_1} \times P_2^{\alpha_2} \times \cdots \times P_k^{\alpha_k} $ ,由欧拉函数公式,$ \phi(P_j \times i) = P_j \times i \times (1 - \frac{1}{P_1}) \times (1 - \frac{1}{P_2}) \times \cdots \times (1 - \frac{k}{P_k}) = P_j \times \phi(i) $
    ③ $ P_j $ 不是 $ i $ 的质因子,由于 $ i = P_1^{\alpha_1} \times P_2^{\alpha_2} \times \cdots \times P_k^{\alpha_k} $ ,$ P_j $ 必不在 $ P_1 $ ~ $ P_k $ 中,那么 $ P_j \times i = P_j \times P_1^{\alpha_1} \times P_2^{\alpha_2} \times \cdots \times P_k^{\alpha_k} $ ,由欧拉函数公式,$ \phi(P_j \times i) = P_j \times (1 - \frac{1}{P_j}) \times i \times (1 - \frac{1}{P_1}) \times (1 - \frac{1}{P_2}) \times \cdots \times (1 - \frac{k}{P_k}) = P_j \times (1 - \frac{1}{P_j}) \times \phi(i) $

标签:phi,frac,筛法,int,874,times,cdots,alpha,AcWing
来源: https://www.cnblogs.com/wKingYu/p/16248654.html