最大公约数

AcWing-220-最大公约数open in new window

实现

#include <iostream>
using namespace std;

typedef long long LL;
const int N = 10000010;
int n;
int idx, primes[N], phi[N];
bool mark[N];
LL sum[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);
    for (int i = 1; i <= n; ++ i) sum[i] = sum[i - 1] + phi[i];
    LL res = 0;
    for (int i = 1; i <= idx; ++ i)
        res += 2 * (sum[n / primes[i]] - sum[1]) + 1;
    cout << res << endl;
    return 0;
}
最后修改于: