标签:lcm void class open pen file rac getc long
求 \(\sum_{i=1}^nlcm(i,n)\) 。
原式可以化为
\[\sum_{i=1}^n\frac{i*n}{gcd(i,n)}\]
由于 \(gcd(i,n)=gcd(n-i,n)\) ,可将原式变形为
\[\frac{1}{2}(\sum_{i=1}^{n-1}\frac{i*n}{gcd(i,n)}+\sum_{i=n-1}^{1}\frac{i*n}{gcd(i,n)})+n\]
两边的 \(sum\) 对应相等,于是有
\[\frac{1}{2}\sum_{i=1}^{n-1}\frac{n^2}{gcd(i,n)}+n\]
将 \(gcd(i,n)\) 相等的放在一起统计,枚举 \(gcd(i,n)==d\) ,则 \(gcd(\frac{i}{d},\frac{n}{d})==1\) ,故 \(gcd(i,n)==d\) 的数量为 \(\varphi(\frac{n}{d})\) 。
\[\frac{1}{2}\sum_{d|n}\frac{\varphi(\frac{n}{d})*n^2}{d}+n\]
转换枚举顺序,令 \(d'=\frac{n}{d}\) ,上式化为
\[\frac{n}{2}\sum_{d'|n}\varphi(d')*d'+n\]
设 \(g(n)=\sum_{d|n}\varphi(d)*d\) ,已知 \(g(n)\) 为积性函数,则可以预处理出答案,直接输出即可。
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define N 1000000
#define il inline
#define re register
#define tie0 cin.tie(0),cout.tie(0)
#define fastio ios::sync_with_stdio(false)
#define File(x) freopen(x".in","r",stdin);freopen(x".out","w",stdout)
using namespace std;
typedef long long ll;
template <typename T> inline void read(T &x) {
T f = 1; x = 0; char c;
for (c = getchar(); !isdigit(c); c = getchar()) if (c == '-') f = -1;
for ( ; isdigit(c); c = getchar()) x = x * 10 + (c ^ 48);
x *= f;
}
int n;
ll ans[N+5];
int phi[N+5], prime[N+5];
bool vis[N+5];
void get_phi() {
int cnt = 0;
phi[1] = 1;
for (int i = 2; i <= N; ++i) {
if (!vis[i]) prime[++cnt] = i, phi[i] = i - 1;
for (int j = 1; j <= cnt && i * prime[j] <= N; ++j) {
vis[i*prime[j]] = 1;
if (i % prime[j] == 0) {
phi[i*prime[j]] = phi[i] * prime[j];
break;
}
phi[i*prime[j]] = phi[i] * (prime[j] - 1);
}
}
}
void pre() {
for (int i = 1; i <= N; ++i)
for (int j = 1; j * i <= N; ++j)
ans[i*j] += 1ll * j * phi[j] / 2;
for (int i = 1; i <= N; ++i) ans[i] = 1ll * ans[i] * i + i;
}
int main() {
get_phi();
pre();
int t;
read(t);
while (t--) {
read(n);
printf("%lld\n", ans[n]);
}
return 0;
}
标签:lcm void class open pen file rac getc long
原文地址:https://www.cnblogs.com/hlw1/p/11562195.html