P2522 [HAOI2011] Problem b
题意
求 \(\sum_{i = a} ^ {b} \sum_{j = c} ^ {d} [\gcd(i, j) = k]\)。
Sol
简单容斥一下。
\[\begin{aligned}
\sum_{i = a} ^ {b} \sum_{j = c} ^ {d} [\gcd(i, j) = k]
&= \sum_{i = 1} ^ {b} \sum_{j = 1} ^ {d} [\gcd(i, j) = k] \\
&- \sum_{i = 1} ^ {b} \sum_{j = 1} ^ {c - 1} [\gcd(i, j) = k] \\
&- \sum_{i = 1} ^ {a - 1} \sum_{j = 1} ^ {d} [\gcd(i, j) = k] \\
&+ \sum_{i = 1} ^ {a - 1} \sum_{j = 1} ^ {c - 1} [\gcd(i, j) = k]
\end{aligned}\]
发现 \(i, j\) 都从 \(1\) 开始。与 P3455 相同。
Code
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <array>
#include <bitset>
#define int long long
using namespace std;
#ifdef ONLINE_JUDGE
#define getchar() (p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, 1 << 21, stdin), p1 == p2) ? EOF : *p1++)
char buf[1 << 23], *p1 = buf, *p2 = buf, ubuf[1 << 23], *u = ubuf;
#endif
int read() {
int p = 0, flg = 1;
char c = getchar();
while (c < '0' || c > '9') {
if (c == '-') flg = -1;
c = getchar();
}
while (c >= '0' && c <= '9') {
p = p * 10 + c - '0';
c = getchar();
}
return p * flg;
}
void write(int x) {
if (x < 0) {
x = -x;
putchar('-');
}
if (x > 9) {
write(x / 10);
}
putchar(x % 10 + '0');
}
const int N = 1e5 + 5;
array <int, N> p, mu;
bitset <N> vis;
int cnt;
void Euler(int n) {
mu[1] = 1;
for (int i = 2; i <= n; i++) {
if (!vis[i]) {
cnt++;
p[cnt] = i;
mu[i] = -1;
}
for (int j = 1; j <= cnt && i * p[j] <= n; j++) {
vis[i * p[j]] = 1;
if (i % p[j] == 0) {
mu[i * p[j]] = 0;
break;
}
mu[i * p[j]] = -mu[i];
}
}
for (int i = 1; i <= n; i++)
mu[i] += mu[i - 1];
}
int query(int n, int m, int k) {
n /= k, m /= k;
if (n > m) swap(n, m);
int res = 0, ans = 0;
for (int i = 1; i <= n; i = res + 1) {
res = min(n / (n / i), m / (m / i));
ans += (mu[res] - mu[i - 1]) * (n / i) * (m / i);
}
return ans;
}
void solve() {
int a = read(), b = read(), c = read(), d = read(), k = read();
write(query(b, d, k) - query(b, c - 1, k) - query(a - 1, d, k) + query(a - 1, c - 1, k)), puts("");
}
signed main() {
Euler(1e5);
int T = read();
while (T--) solve();
return 0;
}