luoguP2303 [SDOI2012]Longge的问题 化式子

\(\sum \limits_{i = 1}^n gcd(i, n)\)


\(\sum \limits_{i = 1}^n gcd(i, n)\)

\(=\sum \limits_{i = 1}^n \sum\limits_{d|i\;and\;d|n} \varphi(d)\)

\(=\sum \limits_{d |n} \varphi(d) * \frac{n}{d}\)

然后就可以以一个很低的复杂度过了

反正复杂度是不会超过\(O(\sqrt n * d(n))\)


#include <bits/stdc++.h>
using namespace std;

#define ll long long

ll n, ans;

inline ll phi(ll m) {
    ll ret = m;
    for(ll t = 2; t * t <= m; t ++)
    if(m % t == 0) {
        while(m % t == 0) m /= t;
        ret /= t; ret *= (t - 1);
    }
    if(m > 1) ret /= m, ret *= (m - 1);
    return ret;
}

int main() {
    cin >> n;
    for(ll i = 1; i * i <= n; i ++) 
    if(n % i == 0) {
        ans += phi(i) * (n / i);
        if(n / i != i) ans += phi(n / i) * i;
    }
    printf("%lld\n", ans);
    return 0;
}
posted @ 2018-12-18 17:34  remoon  阅读(154)  评论(0编辑  收藏  举报