P4450 双亲数
$$
\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}
$$
查看代码
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 = 1e6 + 10; int n, m, k; 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%d%d", &n, &m, &k); n /= k, m /= k; LL res = 0; for (int l = 1, r; l <= min(n, m); 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; }
|