月月给华华出题
思路
∑i=1nigcd(i,n)\sum_{i = 1} ^{n} \frac{i}{gcd(i, n)}i=1∑ngcd(i,n)i
=∑d∣n∑i=1nid(gcd(i,d)==d)= \sum _{d \mid n} \sum_{i = 1} ^{n} \frac{i}{d} (gcd(i, d) == d)=d∣n∑i=1∑ndi(gcd(i,d)==d)
=∑d∣n∑i=1ndi(gcd(i,d)==1)= \sum_{d\mid n} \sum_{i = 1} ^{\frac{n}{d}} i(gcd(i, d) == 1)=d∣n∑i=1∑dni(gcd(i,d)==1)
=∑d∣nnd∗ϕ(nd)2= \sum_{d \mid n} \frac{\frac{n}{d} * \phi(\frac{n}{d})} {2}=d∣n∑2dn∗ϕ(dn)
结果就出来了,我们只要仿照埃氏筛法,统计一遍答案就行了。
代码
/*Author : lifehappy
*/
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>#define mp make_pair
#define pb push_back
#define endl '\n'
#define mid (l + r >> 1)
#define lson rt << 1, l, mid
#define rson rt << 1 | 1, mid + 1, r
#define ls rt << 1
#define rs rt << 1 | 1using 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 x = 0, f = 1; 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 x * f;
}const int N = 5e6 + 10;int phi[N], n;bool st[N];vector<int> prime;ll sum[N], ans[N];void init() {st[0] = st[1] = 1;phi[1] = 1, sum[1] = 1;//注意把sum[1]置为1,特判。for(int i = 2; i < N; i++) {if(!st[i]) {prime.pb(i);phi[i] = i - 1;sum[i] = 1ll * i * phi[i] / 2;}for(int j = 0; j < prime.size() && i * prime[j] < N; j++) {st[i * prime[j]] = 1;if(i % prime[j]) {phi[i * prime[j]] = phi[i] * (prime[j] - 1);sum[i * prime[j]] = 1ll * phi[i * prime[j]] * (i * prime[j]) / 2;}else {phi[i * prime[j]] = phi[i] * prime[j];sum[i * prime[j]] = 1ll * phi[i * prime[j]] * (i * prime[j]) / 2;break;}}}for(int i = 1; i < N; i++) {for(int j = i; j < N; j += i) {ans[j] += sum[i];}}
}int main() {// freopen("in.txt", "r", stdin);// freopen("out.txt", "w", stdout);ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);init();n = read();for(int i = 1; i <= n; i++)cout << ans[i] << "\n";return 0;
}