BZOJ 2820. YY的GCD
$$\sum_{i=1}^{n}\sum_{i=1}^{m}\left[\left(i,j\right)\in P\right]$$
$$=\sum_{p\in P}\sum_{i=1}^{n}\sum_{i=1}^{m}\left[\left(i,j\right)=p\right]$$$$=\sum_{p\in P}\sum_{i=1}^{\lfloor \frac{n}{p} \rfloor}\sum_{i=1}^{\lfloor \frac{m}{p} \rfloor}\left[\left(i,j\right)=1\right]$$
$$=\sum_{p\in P}\sum_{d=1}^{\min\{\lfloor \frac{n}{p} \rfloor,\lfloor \frac{m}{p} \rfloor\}}\mu(d)\lfloor\frac{n}{pd}\rfloor\lfloor\frac{m}{pd}\rfloor$$
$$=\sum_{T=1}^{\min\{n, m\}}\lfloor\frac{n}{T}\rfloor\lfloor\frac{m}{T}\rfloor\sum_{p|T \wedge p\in P}\mu(\frac{T}{p})$$
$f(n) = \sum_{p|n \wedge p \in P}\mu(\frac{n}{p})$ 不是积性函数,但是可以线性筛预处理出来。
对于质数 $p$,$f(p)=1$
当 $p < M(i)$ 时,$f(i \times p)=-f(i)+\mu(i)$
当 $p=M(i)$ 时,$i \times p$ 里含有 $p^2$,所以 $\forall p' \neq p$,$\mu(\frac{i\times p}{p'})=0$,所以 $f(i\times p)=\mu(i)$
#include <bits/stdc++.h> #define ll long long const int N = 1e7 + 7; int prime[N], prin, mu[N]; bool vis[N]; ll f[N]; void init() { mu[1] = 1; for (int i = 2; i < N; i++) { if (!vis[i]) { prime[++prin] = i; mu[i] = -1; f[i] = 1; } for (int j = 1; j <= prin && i * prime[j] < N; j++) { vis[i * prime[j]] = 1; if (i % prime[j] == 0) { mu[i * prime[j]] = 0; f[i * prime[j]] = mu[i]; break; } mu[i * prime[j]] = -mu[i]; f[i * prime[j]] = -f[i] + mu[i]; } } for (int i = 1; i < N; i++) f[i] += f[i - 1]; } ll solve(int n, int m) { ll ans = 0; for (int i = 1, j; i <= std::min(n, m); i = j + 1) { j = std::min(n / (n / i), m / (m / i)); ans += (f[j] - f[i - 1]) * (n / i) * (m / i); } return ans; } int main() { init(); int T; scanf("%d", &T); while (T--) { int n, m; scanf("%d%d", &n, &m); printf("%lld\n", solve(n, m)); } return 0; }