仪仗队

洛谷-P2158-仪仗队open in new window

分析

见《进阶指南》第147页。

实现

#include <iostream>
using namespace std;

const int N = 40010;
int n;
int idx, primes[N], phi[N];
bool mark[N];

void get_phi (int n) {
    phi[1] = 1;
    for (int i = 2; i <= n; ++ i) {
        if (mark[i] == false) {
            primes[++ idx] = i;
            phi[i] = i - 1;
        }
        for (int j = 1; primes[j] <= n / i; ++ j) {
            mark[i * primes[j]] = true;
            if (i % primes[j] == 0) {
                phi[i * primes[j]] = phi[i] * primes[j];
                break;
            } else {
                phi[i * primes[j]] = phi[i] * (primes[j] - 1);
            }
        }
    }
}

int main () {
    cin >> n;

    get_phi(n);
    if (n == 1) {
        cout << 0 << endl;
    } else {
        int res = 0;
        for (int i = 2; i <= n - 1; ++ i) res += phi[i];
        cout << res * 2 + 3 << endl;
    }
    return 0;
}
最后修改于: