BZOJ4804: 欧拉心算(莫比乌斯反演 线性筛)

时间:2021-12-02 16:49:56

题意

求$$\sum_1^n \sum_1^n \phi(gcd(i, j))$$

$T \leqslant 5000, N \leqslant 10^7$

Sol

延用BZOJ4407的做法

化到最后可以得到

$$\sum_{T = 1}^n \frac{n}{T} \frac{n}{T} \sum_{d \mid T}^n \phi(d) \mu(\frac{T}{d})$$

后面的那个是积性函数,直接筛出来

注意这个函数比较特殊,筛的时候需要分几种情况讨论

1. $H(p) = p - 2$

2. $H(p^2) = p^2 - 2p + 1$

3. $H(p^{k + 1}) = H(p^k) * p$

// luogu-judger-enable-o2
#include<cstdio>
#include<algorithm>
#define LL long long
using namespace std;
const int MAXN = 1e7 + , mod = 1e9 + ;
inline int read() {
char c = getchar(); int x = , f = ;
while(c < '' || c > '') {if(c == '-') f = -; c = getchar();}
while(c >= '' && c <= '') x = x * + c - '', c = getchar();
return x * f;
}
int prime[MAXN], vis[MAXN], tot;
LL H[MAXN], low[MAXN];
void GetH(int N) {
H[] = vis[] = ;
for(int i = ; i <= N; i++) {
if(!vis[i]) prime[++tot] = i, H[i] = i - , low[i] = i;
for(int j = ; j <= tot && i * prime[j] <= N; j++) {
vis[i * prime[j]] = ;
if(!(i % prime[j])) {
low[i * prime[j]] = low[i] * prime[j];
if(low[i] == i) {
if(low[i] == prime[j]) H[i * prime[j]] = (H[i] * prime[j] + );
else H[i * prime[j]] = H[i] * prime[j];
}
else H[i * prime[j]] = H[i / low[i]] * H[low[i] * prime[j]];
break;
}
H[i * prime[j]] = H[i] * H[prime[j]];
low[i * prime[j]] = prime[j];
}
}
for(int i = ; i <= N; i++)
H[i] = H[i - ] + H[i];
}
int main() {
GetH(1e7 + );
int T = read();
while(T--) {
int N = read(), last;
LL ans = ;
for(int i = ; i <= N; i = last + ) {
last = N / (N / i);
ans = ans + 1ll * (N / i) * (N / i) * (H[last] - H[i - ]);
}
printf("%lld\n", ans);
}
return ;
}
/*
3
7001
123000
10000000
*/