[BZOJ 3944]Sum

题目大意

求$\Sigma_{i = 1}^{n}{\phi(i)}$和$\Sigma_{i = 1}^{n}{\mu(i)}$,$n \leq 2 ^ {31} - 1$


思路

杜教筛

有$F(n) = \Sigma_{i = 1}^{n}{f(i)}$

$\Sigma_{i = 1}^{n}(f * g)(i) = \Sigma_{i = 1}^{n}{g(i)F([\frac{n}{i}])}$

则$g(1)F(n) = \Sigma_{i = 1}^{n}{f * g}(i) - \Sigma_{i = 2}^{n}{g(i)F[\frac{n}{i}]}$

$g$一般取恒等函数$I$

据说将$O(n^{\frac{2}{3}})$内的$F(i)$预处理,复杂度可达到$O(n^{\frac{2}{3}})$

Conclusion

$\Sigma{\phi(i)} = \frac{n(n + 1)}{2} - \Sigma_{i = 2}^{n}{F([\frac{n}{i}])}$

$\Sigma{\mu(i)} =1-\sum_{i=2}^{n}F(\frac{n}{i})$

开map记忆化搜索


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
typedef long long LL;
#define N 4000050
LL cnt,vis[N],prime[N / 5],mu[N],phi[N];
std::map<int,LL> _phi,_mu;
inline void sieve()
{
mu[1] = phi[1] = 1;
for(register int i = 2;i < N;i++)
{
if(!vis[i]){mu[i] = -1;phi[i] = i - 1;prime[++cnt] = i;}
for(register int j = 1,k = prime[j];j <= cnt && i * (k = prime[j]) <= N;j++)
{
vis[i * k] = 1;
if(i % k)
{
phi[i * k] = phi[i] * phi[k];
mu[i * k] = -mu[i];
}
else
{
phi[i * k] = phi[i] * k;
break;
}
}
}
for(register int i = 1;i < N;i++) phi[i] += phi[i - 1],mu[i] += mu[i - 1];
}
inline LL calc_mu(LL n)
{
if(n < N) return mu[n];
std::map<int,LL>::iterator it = _mu.find(n);
if(it != _mu.end()) return it->second;
LL ret = 1,last;
for(unsigned i = 2;i <= n;i = last + 1)
{
last = n / (n / i);
ret -= (last - i + 1) * calc_mu(n / i);
}
return _mu[n] = ret;
}
inline LL calc_phi(LL n)
{
if(n < N) return phi[n];
std::map<int,LL>::iterator it = _phi.find(n);
if(it != _phi.end()) return it->second;
LL ret = (LL)n * (n + 1) >> 1,last;
for(unsigned i = 2;i <= n;i = last + 1)
{
last = n / (n / i);
ret -= (last - i + 1) * calc_phi(n / i);
}
return _phi[n] = ret;
}
int main()
{
sieve();
int T;scanf("%d",&T);while(T--)
{
LL n;scanf("%lld",&n);if(!n)printf("0 0\n");
else printf("%lld %lld\n",calc_phi(n),calc_mu(n));
}
return 0;
}