杜教筛
杜教筛是用来快速求解一个数论函数
考虑给
移项得到:
如果我们选取的
时间复杂度
时间复杂度的证明咕咕咕。。。
常用的几对
-
\mu ∗ I = \epsilon -
\varphi * I = id -
\mu * id = \varphi -
f * \epsilon = f
贴个筛
#include <bits/stdc++.h>
#define int long long
#define il inline
using namespace std;
const int B = (1 << 20);
int ttt, n, sp[B], sm[B], phi[B], mu[B], p[B], tot;
bool np[B];
il void init() {
phi[1] = mu[1] = 1;
for (int i = 2; i < B; i++) {
if (!np[i]) p[++tot] = i, phi[i] = i - 1, mu[i] = -1;
for (int j = 1; j <= tot and i * p[j] < B; j++) {
np[i * p[j]] = 1;
if (i % p[j] == 0) {
phi[i * p[j]] = phi[i] * p[j];
mu[i * p[j]] = 0;
break;
} else {
phi[i * p[j]] = phi[i] * phi[p[j]];
mu[i * p[j]] = -mu[i];
}
}
}
for (int i = 1; i < B; i++) {
sp[i] = sp[i - 1] + phi[i];
sm[i] = sm[i - 1] + mu[i];
}
}
map<int, int> Smu, Sphi;
il int sphi(int n) {
if (n < B) return sp[n];
if (Sphi[n]) return Sphi[n];
int res = n * (n + 1) / 2;
for (int l = 2, r; l <= n; l = r + 1) {
r = n / (n / l);
res -= (r - l + 1) * sphi(n / l);
}
return Sphi[n] = res / 1;
}
il int smu(int n) {
if (n < B) return sm[n];
if (Smu[n]) return Smu[n];
int res = 1;
for (int l = 2, r; l <= n; l = r + 1) {
r = n / (n / l);
res -= (r - l + 1) * smu(n / l);
}
return Smu[n] = res / 1;
}
il void solve() {
cin >> n;
cout << sphi(n) << ' ' << smu(n) << '\n';
}
signed main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
init();
cin >> ttt;
while (ttt--) solve();
}