求 (displaystylesum_{i=1}^ngcd(i,n))
(nleq2^{32})
数论
首先考虑将原式化为 $$displaystylesum_{k|n}sum_{i=1}^{frac{n}{k}}{[gcd(i,frac{n}{k})=1]}$$
我们发现右边其实就是欧拉函数,即 $$displaystylesum_{k|n}varphi(frac{n}{k})$$
然后就直接求就好辣
注意 (long long),以及完全平方数的特判
时间复杂度 (O(sqrt n))
代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll n;
ll get_phi(ll x) {
int t = sqrt(x); ll res = x;
for (int i = 2; i <= t; i++) {
if (x % i == 0) {
res = res / i * (i - 1);
while (x % i == 0) x /= i;
}
}
return x > 1 ? res / x * (x - 1) : res;
}
int main() {
scanf("%lld", &n);
int t = sqrt(n); ll ans = 0;
for (int i = 1; i <= t; i++) {
if (n % i == 0) {
ans += i * get_phi(n / i) + n / i * get_phi(i);
}
}
if (1ll * t * t == n) ans -= t * get_phi(t);
printf("%lld", ans);
return 0;
}