#6229. 这是一道简单的数学题

#6229. 这是一道简单的数学题(反演 + 杜教筛)_ios

代码

/*
  Author : lifehappy
*/
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>
#define endl "\n"

using namespace std;

typedef long long ll;

const int inf = 0x3f3f3f3f;
const double eps = 1e-7;

const int mod = 1e9 + 7, N = 1e6 + 10, inv6 = 166666668, inv2 = 500000004;

int prime[N], mu[N], cnt;

ll sum[N];

bool st[N];

ll quick_pow(ll a, int n) {
    ll ans = 1;
    while(n) {
        if(n & 1) ans = ans * a % mod;
        a = a * a % mod;
        n >>= 1;
    }
    return ans;
}

void init() {
    mu[1] = 1;
    for(int i = 2; i < N; i++) {
        if(!st[i]) {
            prime[cnt++] = i;
            mu[i] = -1;
        }
        for(int j = 0; j < cnt && i * prime[j] < N; j++) {
            st[i * prime[j]] = 1;
            if(i % prime[j] == 0)   break;
            mu[i * prime[j]] = -mu[i];
        }
    }
    for(int i = 1; i < N; i++) {
        for(int j = i; j < N; j += i) {
            sum[j] = (sum[j] + 1ll * i * i % mod * mu[i] % mod + mod) % mod;
        }
    }
    for(int i = 1; i < N; i++) {
        sum[i] = (sum[i] + sum[i - 1]) % mod;
    }
}

ll calc1(ll n) {
    ll ans = 1ll * (1 + n) * n / 2 % mod;
    return 1ll * ans * ans % mod;
}

ll calc2(ll n) {
    return 1ll * n * (n + 1) % mod * (2 * n + 1) % mod * inv6 % mod;
}

unordered_map<int, int> ans_s;

ll S(int n) {
    if(n < N) return sum[n];
    if(ans_s.count(n)) return ans_s[n];
    ll ans = n;
    for(ll l = 2, r; l <= n; l = r + 1) {
        r = n / (n / l);
        ans = (ans - 1ll * (calc2(r) - calc2(l - 1) + mod) % mod * S(n / l) % mod + mod) % mod;
    }
    return ans_s[n] = ans;
}

int main() {
    // freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
    // ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    // cout << quick_pow(2, mod - 2) << endl;
    init();
    ll n, ans = 0;
    scanf("%lld", &n);
    for(ll l = 1, r; l <= n; l = r + 1) {
        r = n / (n / l);
        ans = (ans + 1ll * calc1(n / l) * ((S(r) - S(l - 1) + mod) % mod) % mod) % mod;
    }
    printf("%lld\n", 1ll * (ans + n) * inv2 % mod);
	return 0;
}