結果

問題 No.2249 GCDistance
ユーザー Today03
提出日時 2025-02-13 20:36:57
言語 C++23
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 1,522 ms / 5,000 ms
コード長 1,200 bytes
コンパイル時間 3,651 ms
コンパイル使用メモリ 276,808 KB
実行使用メモリ 159,392 KB
最終ジャッジ日時 2025-02-13 20:37:20
合計ジャッジ時間 20,896 ms
ジャッジサーバーID
(参考情報)
judge1 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 1
other AC * 10
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int INF = 1e9 + 10;
const ll INFL = 4e18;

/*
    考察
    dist(i,j)=
        1(gcd(i,j)=1)
        2(else)
*/

// phi[0] ... phi[n] を前計算する O(n log(log(n)))
// phi[i] = i以下であって、iと互いに素な数の個数
// ref: https://qiita.com/drken/items/3beb679e54266f20ab63
// ref: https://manabitimes.jp/math/667
// 公式: phi[n] = n * Π(1-1/p) (pはnの素因数)
// 公式: phi[n]phi[m] = phi[nm] (nとmが互いに素)
// 公式: Σ(d|n)phi[d] = n
// 公式: a^phi(m) ≡ 1 (mod m) (aとmが互いに素)
vector<ll> totientTable(ll n) {
    vector<ll> ret(n + 1);
    iota(ret.begin(), ret.end(), 0);
    for (ll i = 2; i <= n; i++) {
        if (ret[i] == i) {
            for (ll j = i; j <= n; j += i) ret[j] = ret[j] / i * (i - 1);
        }
    }
    return ret;
}

int main() {
    int T;
    cin >> T;

    const int mx = 1e7 + 5;
    auto tot = totientTable(mx);
    tot[1]--;
    vector<ll> pref(mx + 1);
    for (int i = 1; i < mx; i++) pref[i + 1] = pref[i] + tot[i] + (i - tot[i] - 1) * 2;

    while (T--) {
        int N;
        cin >> N;
        cout << pref[N + 1] << '\n';
    }
}
0