P2257 YY的GCD
对于每个质数 $n$ ,有
$$
\begin {aligned}
f(n) = & \sum_{i = 1} ^ a \sum_{j = 1} ^ b [ gcd(i, j) = n ] \\
= & \sum_{i = 1} ^ {\frac a n} \sum_{j = 1} ^ {\frac b n} \sum_{d | gcd(i, j)} \mu(d) \\
= & \sum_{i = 1} ^ {\frac a n} \sum_{j = 1} ^ {\frac b n} \sum_{d | gcd(i, j)} \mu(d) \\
= & \sum_{d = 1} ^ {min({\frac a n}, {\frac b n})} \mu (d) \left \lfloor \frac a {dn} \right \rfloor \left \lfloor \frac b {dn} \right \rfloor \\
\end {aligned}
$$
令
$$
T = dn
$$
则
$$
f(n) = \sum_{T = 1} ^ {min(a, b)} \mu (\frac T n) \left \lfloor \frac a T \right \rfloor \left \lfloor \frac b T \right \rfloor \\
$$
其中前半部分可以预处理,对于每个质数的倍数累加进去。
查看代码
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
| #include <cstdio> #include <algorithm> using namespace std; typedef long long LL; const int N = 1e7 + 10; int cnt; LL low[N], primes[N], mu[N], f[N], s[N]; void init() { mu[1] = 1; low[1] = 1; for (int i = 2; i < N; i++) { if (!low[i]) { primes[++cnt] = i; mu[i] = -1; low[i] = i; } for (int j = 1; j <= cnt && i * primes[j] < N; j++) { if (i % primes[j] == 0) { if (low[i] == primes[j]) mu[i * primes[j]] = 0; else mu[i * primes[j]] = mu[i / low[i]] * mu[primes[j] * low[i]]; low[i * primes[j]] = low[i] * primes[j]; break; } mu[i * primes[j]] = mu[i] * mu[primes[j]]; low[i * primes[j]] = primes[j]; } } for (int i = 1; i <= cnt; i++) for (int j = 1; j * primes[i] < N; j++) f[j * primes[i]] += mu[j]; for (int i = 1; i < N; i++) s[i] = s[i - 1] + f[i]; } int main() { init(); int T; scanf("%d", &T); for (int n, m; T; T--) { scanf("%d%d", &n, &m); if (n > m) swap(n, m); LL res = 0; for (int l = 1, r; l <= n; l = r + 1) { r = min(n / (n / l), m / (m / l)); res += (s[r] - s[l - 1]) * (LL)(n / l) * (LL)(m / l); } printf("%lld\n", res); } return 0; }
|