abc172D 约数之和
题面:记f(x)表示x的约数个数,例如,12的约数有1,2,3,4,6,12共6个,因此f(12)=6。给定n,求\(\sum_{k=1}^{n}k*f(k)\)。
范围:n<=1E7
思路:用类似素数筛的做法预处理出所有f,然后遍历一次得到答案,时间复杂度O(nloglogn)。
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define rep(i,a,b) for(int i=a; i<=b; i++)
#define per(i,a,b) for(int i=b; i>=a; i--)
const int N = 10000005;
int cnt[N];
void init(int n) {
cnt[1] = 1;
rep(i,2,n) {
cnt[i] += 1;
for (int j = i; j <= n; j += i) {
cnt[j] += 1;
}
}
}
void solve() {
int n;
cin >> n;
init(n);
int ans = 0;
rep(i,1,n) {
ans += i * cnt[i];
}
cout << ans << "\n";
}
signed main() {
cin.tie(0)->sync_with_stdio(0);
int t = 1;
while (t--) solve();
return 0;
}