∑
i
=
1
a
∑
j
=
1
b
[
(
i
,
j
)
=
k
]
=
∑
d
=
1
m
i
n
(
⌊
a
k
⌋
,
⌊
b
k
⌋
)
μ
(
d
)
⌊
⌊
a
k
⌋
d
⌋
⌊
⌊
b
k
⌋
d
⌋
\sum_{i=1}^a\sum_{j=1}^b[(i,j)=k]=\sum_{d=1}^{min(\lfloor \frac{a}k\rfloor,\lfloor\frac{b}k\rfloor)}\mu(d)\lfloor\frac{\lfloor\frac{a}k\rfloor}d\rfloor\lfloor\frac{\lfloor\frac{b}k\rfloor}d\rfloor
i=1∑aj=1∑b[(i,j)=k]=d=1∑min(⌊ka⌋,⌊kb⌋)μ(d)⌊d⌊ka⌋⌋⌊d⌊kb⌋⌋
预处理莫比乌斯函数的前缀和,每次整除分块求和。
#include <bits/stdc++.h>
#define rll register ll
#define ll long long
using namespace std;
const int N = 5e4+100;
int p[N], prime[N], mu[N], cnt;
void primes(int n){
mu[1] = 1;
for(int i = 2; i <= n; i++){
if(!p[i]) p[i] = prime[++cnt] = i, mu[i] = -1;
for(int j = 1; j <= cnt; j++){
if(prime[j] > n/i) break;
p[i*prime[j]] = prime[j];
mu[i*prime[j]] = -mu[i];
if(i%prime[j] == 0){
mu[i*prime[j]] = 0;
break;
}
}
}
for(int i = 2; i <= n; i++) mu[i] += mu[i-1];
}
ll solve(ll k, ll a, ll b){
ll ans = 0;
for(ll l = 1, r; l <= k; l = r+1){
if(a/l==0 || b/l==0) break;
ll r1 = min(k, a/(a/l));
ll r2 = min(k, b/(b/l));
r = min(r1, r2);
ans += (mu[r]-mu[l-1])*(a/l)*(b/l);
}
return ans;
}
int a, b, d, m;
int main(){
int t;
primes(5e4);
scanf("%d", &t);
while(t--){
scanf("%d%d%d",&a, &b, &d);
m = min(a/d, b/d);
printf("%lld\n", solve(m, a/d, b/d));
}
return 0;
}