# BZOJ4916: 神犇和蒟蒻(杜教筛)

## 题意

$$\sum_{i = 1}^n \mu(i^2)$$

$$\sum_{i = 1}^n \phi(i^2)$$

$n \leqslant 10^9$

## Sol

zz的我看第一问看了10min。

$\phi(i^2) = i\phi(i)$

$\sum_{d | n} \phi(d) = n$

$$g(1)s(n) = \sum_{i = 1}^n g(i)s(\frac{n}{i}) - \sum_{i = 2}^n g(i)s(\frac{n}{i})$$

$(g * s)(i) = \sum_{i = 1}^n i^2 = \frac{n * (n + 1) * (2n + 1)}{6}$

$$s(n) = \frac{n * (n + 1) * (2n + 1)}{6} - \sum_{i = 2}^n i \phi(\frac{n}{i})$$

#include<cstdio>
#include<map>
#define LL long long
using namespace std;
const int MAXN = 1e7 + 10, mod = 1e9 + 7;
const LL inv = 166666668;
int N, prime[MAXN], vis[MAXN], tot;
LL phi[MAXN];
map<int, LL> ans;
void GetPhi(int N) {
vis[1] = phi[1] = 1;
for(int i = 2; i <= N; i++) {
if(!vis[i]) prime[++tot] = i, phi[i] = i - 1;
for(int j = 1; j <= tot && i * prime[j] <= N; j++) {
vis[i * prime[j]] = 1;
if(!(i % prime[j])) {phi[i * prime[j]] = phi[i] * prime[j]; break;}
phi[i * prime[j]] = phi[i] * phi[prime[j]];
}
}
for(int i = 1; i <= N; i++) phi[i] = (1ll * i * phi[i] % mod +  phi[i - 1] % mod) % mod;
}
LL Query(LL x) {
return (x * (x + 1) / 2) % mod;
}
LL S(LL N) {
if(ans[N]) return ans[N];
if(N <= 1e7) return phi[N];
LL sum = N * (N + 1) % mod * (2 * N + 1) % mod * inv % mod, last = 0;
for(int i = 2; i <= N; i = last + 1) {
last = N / (N / i);
sum -= S(N / i) % mod * (Query(last) - Query(i - 1)) % mod;
sum = (sum + mod) % mod;
}
return ans[N] = (sum % mod + mod) % mod;
}
int main() {
GetPhi(1e7);
scanf("%d", &N);
printf("1\n%lld", S(N));
return 0;
}

posted @ 2018-07-19 19:06  自为风月马前卒  阅读(597)  评论(0编辑  收藏  举报