abc172D 约数之和

41 阅读1分钟

题面:记f(x)表示x的约数个数,例如,12的约数有1,2,3,4,6,12共6个,因此f(12)=6。给定n,求i*f(i)的前n项和。

范围:1 <= n <= 1E7

分析:用类似素数筛的做法预处理出所有f,然后遍历一次得到答案,时间复杂度O(nloglogn)。

#include <bits/stdc++.h>
using i64 = long long;
const int N = 10000005;
int cnt[N];
void init(int n) {
    cnt[1] = 1;
    for (int i = 2; i <= n; i++) {
        cnt[i] += 1;
        for (int j = i; j <= n; j += i) {
            cnt[j] += 1;
        }
    }
}
void solve() {
    int n;
    std::cin >> n;
    init(n);
    i64 ans = 0;
    for (int i = 1; i <= n; i++) {
        ans += 1LL * i * cnt[i];
    }
    std::cout << ans << "\n";
}
int main() {
    std::cin.tie(0)->sync_with_stdio(0);
    int t = 1;
    while (t--) solve();
    return 0;
}

标签:数论