AcWing 874.筛法求欧拉函数(模板题)

Issue:在这里插入图片描述

Thinking:

  1. 在线性筛质数下同时把欧拉函数给筛出来;
  2. 如果一个数 i i i 是质数,那么欧拉函数 ϕ ( i ) = i − 1 \phi(i) = i - 1 ϕ(i)=i1
  3. if (i % primes[j] == 0) ϕ ( i ) = i ( 1 − 1 P 1 ) ⋯ ( 1 − 1 P j ) ⋯ ( 1 − 1 P k ) \phi(i) = i(1-\frac{1}{P_1})\cdots(1-\frac{1}{P_j})\cdots(1-\frac{1}{P_k}) ϕ(i)=i(1P11)(1Pj1)(1Pk1),// P j P_j Pj是i的一个质因子,直接用欧拉函数的公式,同时 P j P_j Pj也是 P j × i P_j \times i Pj×i的质因子;
    ϕ ( P j i ) = P j i ( 1 − 1 P 1 ) ⋯ ( 1 − 1 P j ) ⋯ ( 1 − 1 P k ) = P j ϕ ( i ) \phi(P_j i) = P_ji(1-\frac{1}{P_1})\cdots(1-\frac{1}{P_j})\cdots(1-\frac{1}{P_k}) = P_j\phi(i) ϕ(Pji)=Pji(1P11)(1Pj1)(1Pk1)=Pjϕ(i)
  4. if (i % primes[j] != 0 ϕ ( i ) = i ( 1 − 1 P 1 ) ⋯ ( 1 − 1 P k ) \phi(i) = i(1-\frac{1}{P_1})\cdots(1-\frac{1}{P_k}) ϕ(i)=i(1P11)(1Pk1),// P j P_j Pj不是i的质因子,但是 P j × i P_j \times i Pj×i的质因子;
    ϕ ( P j i ) = P j i ( 1 − 1 P 1 ) ⋯ ( 1 − 1 P k ) ( 1 − 1 P j ) = P j ϕ ( i ) ( 1 − 1 P j ) = ( P j − 1 ) ϕ ( i ) \phi(P_ji) = P_ji(1-\frac{1}{P_1})\cdots(1-\frac{1}{P_k})(1-\frac{1}{P_j}) = P_j\phi(i)(1-\frac{1}{P_j}) = (P_j - 1)\phi(i) ϕ(Pji)=Pji(1P11)(1Pk1)(1Pj1)=Pjϕ(i)(1Pj1)=(Pj1)ϕ(i)

Code:

#include <iostream>

using namespace std;

const int N = 1e6 + 10;

int primes[N], cnt;
int phi[N];
bool st[N];

long long euler(int n)
{
    phi[1] = 1;  //1~1中和1互质的数只有1
    for (int i = 2; i <= n; i ++ )
    {
        if (!st[i])
        {
            primes[cnt ++ ] = i;
            phi[i] = i - 1;  //质数i的欧拉函数为i-1
        }
        for (int j = 0; primes[j] <= n / i; j ++ )
        {
            st[primes[j] * i] = true;
            if (i % primes[j] == 0)
            {
                phi[primes[j] * i] = primes[j] * phi[i];
                break;
            }
            phi[primes[j] * i] = (primes[j] - 1) * phi[i];
        }
    }
    
    long long res = 0;
    for (int i = 1; i <= n; i ++ ) 
        res += phi[i];

    return res;
}

int main()
{
    int n;
    cin >> n;
    
    cout << euler(n) << endl;
    
    return 0;
}

Tips:

  1. 欧拉筛模板:
int primes[N], cnt;
int phi[N];
bool st[N];

void euler(int n)
{
    phi[1] = 1;
    for (int i = 2; i <= n; i ++ )
    {
        if (!st[i])
        {
            primes[cnt ++ ] = i;
            phi[i] = i - 1;
        }
        for (int j = 0; primes[j] <= n / i; j ++ )
        {
            st[primes[j] * i] = true;
            if (i % primes[j] == 0)
            {
                phi[primes[j] * i] = primes[j] * phi[i];
                break;
            }
            phi[primes[j] * i] = (primes[j] - 1) * phi[i];
        }
    }
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值