P2303 [SDOI2012] Longge 的问题
思路
我们显然可以枚举每一对数的gcdgcdgcd进行求解,进而我们有如下推导:
=>∑i=1ngcd(i,n)=>\sum _{i = 1} ^ {n} gcd(i, n)=>i=1∑ngcd(i,n)
=>∑d∣nd∑i=1n(gcd(i,d)==d)=>\sum _{d \mid{n}} d \sum _{i = 1} ^ {n} (gcd(i, d) == d)=>d∣n∑di=1∑n(gcd(i,d)==d)
=>∑d∣nd∑i=1nd(gcd(i,d)==1)=>\sum _{d \mid n}d \sum _{i = 1}^{\frac {n} {d}}(gcd(i, d) == 1)=>d∣n∑di=1∑dn(gcd(i,d)==1)
=>∑d∣ndϕ(nd)=>\sum _{d \mid n}d\phi(\frac{n}{d})=>d∣n∑dϕ(dn)
这就简单了,只要枚举nnn的所有因子就行。
代码
/*Author : lifehappy
*/
#pragma GCC optimize(2)
#pragma GCC optimize(3)
// #include <iostream>
// #include <algorithm>
// #include <stdlib.h>
// #include <cmath>
// #include <vector>
// #include <cstdio>
#include <bits/stdc++.h>
#define mp make_pair
#define pb push_back
#define endl '\n'using namespace std;typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;const double pi = acos(-1.0);
const double eps = 1e-7;
const int inf = 0x3f3f3f3f;inline ll read() {ll f = 1, x = 0;char c = getchar();while(c < '0' || c > '9') {if(c == '-') f = -1;c = getchar();}while(c >= '0' && c <= '9') {x = (x << 1) + (x << 3) + (c ^ 48);c = getchar();}return f * x;
}void print(ll x) {if(x < 10) {putchar(x + 48);return ;}print(x / 10);putchar(x % 10 + 48);
}ll eular(ll n) {ll ans = n;for(ll i = 2; i * i <= n; i++) {if(n % i == 0) {while(n % i == 0) n /= i;ans = ans / i * (i - 1);}}if(n != 1) ans = ans / n * (n - 1);return ans;
}int main() {// freopen("in.txt", "r", stdin);// freopen("out.txt", "w", stdout);// ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);ll n = read(), Ans = 0;for(ll i = 1; i * i <= n; i++) {if(n % i == 0) {Ans += i * eular(n / i);if(i * i != n) {Ans += n / i * eular(i);}}}printf("%lld\n", Ans);return 0;
}