P2568 GCD
对于每一个素数 $p$ ,对答案的贡献为:
$$
\begin{aligned}
&\sum _ {i = 1} ^ n \sum _ {j = 1} ^ n [gcd(i, j) = p]\\
=& \sum _ {i = 1} ^ n \sum _ {j = 1} ^ n \sum _ {d | gcd(\left \lfloor \frac i p\right \rfloor, \left \lfloor \frac j p\right \rfloor)} \mu (d)\\
=& \sum _ {i = 1} ^ \left \lfloor \frac n p\right \rfloor \sum _ {j = 1} ^ \left \lfloor \frac n p\right \rfloor \sum _ {d | i \wedge d | j} \mu (d)\\
=& \sum _ {d = 1} ^ \left \lfloor \frac n p\right \rfloor \mu (d) \sum _ {i = 1} ^ \left \lfloor \frac n p\right \rfloor [d |i] \sum _ {i = 1} ^ \left \lfloor \frac n p\right \rfloor [d |j]\\
=& \sum _ {d = 1} ^ \left \lfloor \frac n p\right \rfloor \mu (d) \left \lfloor \frac n {pd} \right \rfloor ^ 2\\
\end{aligned}
$$
筛出所有质数,同时筛出 $\mu$ 并预处理前缀和,询问时可以数论分块。
查看代码
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
| #include <cstdio> #include <algorithm> using namespace std; typedef long long LL; const int N = 1e7 + 10; int n; bool vis[N]; int cnt, primes[N], mu[N]; LL s[N]; void init() { mu[1] = 1; for (int i = 2; i < N; i++) { if (!vis[i]) { primes[++cnt] = i; mu[i] = -1; } for (int j = 1; j <= cnt && i * primes[j] < N; j++) { vis[primes[j] * i] = true; if (i % primes[j] == 0) { mu[primes[j] * i] = 0; break; } mu[primes[j] * i] = -mu[i]; } } for (int i = 1; i < N; i++) s[i] = s[i - 1] + mu[i]; } int main() { init(); scanf("%d", &n); LL res = 0; for (int i = 1; primes[i] <= n; i++) for (int l = 1, r; l <= n / primes[i]; l = r + 1) { r = n / (n / l); res += (s[r] - s[l - 1]) * (LL)(n / primes[i] / l) * (LL)(n / primes[i] / l); } printf("%lld", res); return 0; }
|