[SDOi2012]Longge的问题
嘟嘟嘟
.
\[\begin{align*}
ans
&= \sum_{i = 1} ^ {n} (i, n) \\
&= \sum _ {d | n} ^ {n} \sum _ {(i, n) = d} ^ {n} d \\
&= \sum _ {d | n} ^ {n} \sum _ {(i, \frac{n}{d}) = 1} ^ {\frac{n}{d}} d \\
&= \sum _ {d | n} ^ {n} d * \varphi(\frac{n}{d})
\end{align*}\]
然后\(O(\sqrt{n})\)枚举\(n\)的因数,\(O(\sqrt{n})\)求欧拉函数即可。时间复杂度为\(O(\)因数个数$ * \sqrt{n})$。
#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
#define enter puts("")
#define space putchar(' ')
#define Mem(a, x) memset(a, x, sizeof(a))
#define rg register
typedef long long ll;
typedef double db;
const int INF = 0x3f3f3f3f;
const db eps = 1e-8;
//const int maxn = ;
inline ll read()
{
ll ans = 0;
char ch = getchar(), last = ' ';
while(!isdigit(ch)) last = ch, ch = getchar();
while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
if(last == '-') ans = -ans;
return ans;
}
inline void write(ll x)
{
if(x < 0) x = -x, putchar('-');
if(x >= 10) write(x / 10);
putchar(x % 10 + '0');
}
ll phi(ll n)
{
ll ret = n;
for(ll i = 2; i * i <= n; ++i)
if(n % i == 0)
{
ret = ret / i * (i - 1);
while(n % i == 0) n /= i;
}
if(n > 1) ret = ret / n * (n - 1);
return ret;
}
ll solve(ll n)
{
ll ret = 0, i = 1;
for(; i * i < n; ++i)
if(n % i == 0) ret += n / i * phi(i) + i * phi(n / i);
if(i * i == n) ret += i * phi(i);
return ret;
}
int main()
{
ll n = read();
write(solve(n)), enter;
return 0;
}