Luogu P2303 [SDOI2012] Longge 的问题
\(\sum\limits_{i=1}^{n}gcd(i,n)\)
\(=\sum\limits_{d=1}^{n}d \sum\limits_{i=1}^{n}[gcd(i,n)=d]\)
\(=\sum\limits_{d=1}^{n}d \sum\limits_{i=1}^{\frac{n}{d}} [gcd(i,\frac{n}{d})=1](d|i,d|n)\)
考虑欧拉函数的定义,\(\varphi(x) = \sum\limits_{i=1}^{x}[gcd(i,x)=1]\)
\(=\sum\limits_{d=1}^{n} d\times\varphi(\frac{n}{d})(d|n)\)
\(=\sum\limits_{d|n} d\times\varphi(\frac{n}{d})\)
枚举\(x\)的因数\(d\),再枚举\(d\)的质因子求欧拉函数即可。
code
#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#define MogeKo qwq
using namespace std;
long long n;
long long phi(long long x) {
long long ans = x;
for(long long i = 2; i*i <= x; i++) {
if(x%i == 0) ans = ans / i * (i-1);
while(x%i == 0) x /= i;
}
if(x > 1) ans = ans / x * (x-1);
return ans;
}
long long f(long long x) {
long long ans = 0;
for(long long i = 1; i*i <= x; i++)
if(x%i == 0) {
ans += i*phi(x/i);
if(i*i != x) ans += (x/i)*phi(i);
}
return ans;
}
int main() {
scanf("%lld",&n);
printf("%lld",f(n));
return 0;
}