计蒜客 Convex Hull
$\sum \limits_{i=1}^n\sum\limits_{j=1}^i gay(i)=\sum \limits_{i=1}^ngay(i)(n-i+1)$
就是要求 $gay(n)$,$ngay(n)$ 的前缀和。把 $gay(n)$ 记成 $f(n)$
$$\begin{aligned} & \sum_{i=1}^n f(i)\\=&\sum_{i=1}^n i^2\mu^2(i)\\=& \sum_{i=1}^n i^2 \sum_{d^2|i}\mu(d)\\=& \sum_{d=1}^{\sqrt n} \mu(d) \sum_{i=1}^{n}i^2[d^2|i]\\=& \sum_{d=1}^{\sqrt n} \mu(d)d^4 \sum_{i=1}^{\lfloor \frac{n}{d^2} \rfloor}i^2 \end{aligned}$$
预处理出 $\mu(n)n^4$ 即可。
$nf(n)$ 的求法同上
#include <bits/stdc++.h> #define ll long long const int N = 1e5; int prime[N + 7], prin, mu[N + 7]; bool vis[N + 7]; __int128 fs[N + 7], gs[N + 7]; void init() { mu[1] = 1; for (int i = 2; i <= N; i++) { if (!vis[i]) { prime[++prin] = i; mu[i] = -1; } for (int j = 1; j <= prin && i * prime[j] <= N; j++) { vis[i * prime[j]] = 1; if (i % prime[j] == 0) break; mu[i * prime[j]] = -mu[i]; } } for (int i = 1; i <= N; i++) { fs[i] = fs[i - 1] + __int128(i) * i * i * i * mu[i]; gs[i] = gs[i - 1] + __int128(i) * i * i * i * i * i * mu[i]; } } ll MOD; void M(ll &x) { if (x >= MOD) x -= MOD; if (x < 0) x += MOD; } ll sum2(ll n) { assert(MOD * 6 != 0); return __int128(n) * (n + 1) % (MOD * 6) * (n * 2 + 1) % (MOD * 6) / 6; } ll sum3(ll n) { assert(MOD * 2 != 0); ll temp = __int128(n) * (n + 1) % (MOD * 2) / 2; return __int128(temp) * temp % MOD; } int main() { init(); ll n; while (~scanf("%lld%lld", &n, &MOD)) { ll ans, temp1 = 0, temp2 = 0; for (ll i = 1, j; i * i <= n; i = j + 1) { j = sqrt(n / (n / (i * i))); M(temp1 += __int128(fs[j] - fs[i - 1]) % MOD * sum2(n / (i * i)) % MOD); M(temp2 += __int128(gs[j] - gs[i - 1]) % MOD * sum3(n / (i * i)) % MOD); } M(ans = (__int128(n + 1) * temp1 % MOD - temp2) % MOD); printf("%lld\n", ans); } return 0; }