知识概览

例题展示

欧拉函数

题目链接

活动 - AcWing系统讲解常用算法与数据结构,给出相应代码模板,并会布置、讲解相应的基础算法题目。欧拉函数算法总结-LMLPHPhttps://www.acwing.com/problem/content/875/

题解
代码
#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    int n;
    cin >> n;
    
    while (n--)
    {
        int a;
        cin >> a;
        
        int res = a;
        for (int i = 2; i <= a / i; i++)
            if (a % i == 0)
            {
                res = res / i * (i - 1);
                while (a % i == 0) a /= i;
            }
            
        if (a > 1) res = res / a * (a - 1);
        
        cout << res << endl;
    }
    
    return 0;
}

线性筛法求欧拉函数

题目链接

活动 - AcWing系统讲解常用算法与数据结构,给出相应代码模板,并会布置、讲解相应的基础算法题目。欧拉函数算法总结-LMLPHPhttps://www.acwing.com/problem/content/876/

题解
代码
#include <iostream>
#include <algorithm>

using namespace std;

typedef long long LL;

const int N = 1000010;

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

LL get_eulers(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] = phi[i] * primes[j];
                break;
            }
            phi[primes[j] * i] = phi[i] * (primes[j] - 1);
        }
    }
    
    LL res = 0;
    for (int i = 1; i <= n; i++) res += phi[i];
    return res;
}

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

参考资料

  1. AcWing算法基础课
01-08 13:06