SP5971 LCMSUM - LCM Sum
思路
∑i=1nlcm(i,n)\sum_{i = 1}^{n}lcm(i, n)i=1∑nlcm(i,n)
=>∑i=1ningcd(i,n)=> \sum_{i = 1}^{n}\frac{i n}{gcd(i, n)}=>i=1∑ngcd(i,n)in
=>n∑i=1nigcd(i,n)=> n\sum_{i = 1}^{n}\frac{i}{gcd(i, n)}=>ni=1∑ngcd(i,n)i
我们按照P2303 [SDOI2012] Longge的思路枚举gcd(i,n)gcd(i, n)gcd(i,n)
=>n∑d∣n∑i=1nid(gcd(i,n)==1)=>n\sum_{d\mid n} \sum_{i = 1}^{n} \frac{i}{d}(gcd(i, n) == 1)=>nd∣n∑i=1∑ndi(gcd(i,n)==1)
=>n∑d∣n∑i=1ndi(gcd(i,nd)==1)=>n\sum_{d\mid n}\sum_{i = 1}^{\frac{n}{d}} i(gcd(i, \frac{n}{d}) == 1)=>nd∣n∑i=1∑dni(gcd(i,dn)==1)
这个式子就熟悉了∑i=1ni(gcd(i,n)==1)=nϕ(n)2\sum_{i = 1} ^{n} i(gcd(i, n) == 1) = \frac{n\phi(n)}{2}∑i=1ni(gcd(i,n)==1)=2nϕ(n),给定一个整数nnn小于nnn的数并且与nnn互质的数的和是这个式子,所以上式变成
=>=>n∑d∣ndϕ(d)2=>=>n\sum_{d\mid n}\frac{d\phi(d)}{2}=>=>nd∣n∑2dϕ(d)
所以我们只要枚举nnn的约数就行了。
这里还存在一个问题,对于gcd=d=1gcd = d = 1gcd=d=1的时候,我们统计的答案是没用贡献的,所以我们还要加上lcm(1,n)=nlcm(1, n) = nlcm(1,n)=n得到我们最后的答案,
这里我整体复杂度是O(n)+TnO(n) + T\sqrt nO(n)+Tn,先用素数筛筛选出所有的ϕ(i)\phi(i)ϕ(i),然后再每次计算答案。
第一道自己推出来的数学题,难得啊!!!
代码
/*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);
}const int N = 1e6 + 10;int eular[N], n;vector<int> prime;bool st[N];void init() {st[0] = st[1] = 1;eular[1] = 1;for(int i = 2; i < N; i++) {if(!st[i]) {prime.pb(i);eular[i] = i - 1;}for(int j = 0; j < prime.size() && i * prime[j] < N; j++) {st[i * prime[j]] = 1;if(i % prime[j]) {eular[i * prime[j]] = eular[i] * (prime[j] - 1);}else {eular[i * prime[j]] = eular[i] * prime[j];break;}}}
}int main() {// freopen("in.txt", "r", stdin);// freopen("out.txt", "w", stdout);// ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);init();int T = read();while(T--) {int n = read();ll ans = 0;for(int i = 1; i * i <= n; i++) {if(n % i == 0) {ans += 1ll * i * eular[i] / 2;if(i * i != n) {ans += 1ll * n / i * eular[n / i] / 2;}}cout << ans << endl;}printf("%lld\n", 1ll * n * ans + n);}return 0;
}