∑ x = a b ∑ y = c d [ g c d ( x , y ] = k ] \sum_{x = a}^b\sum_{y = c}^d [gcd(x,y] = k] ∑x=ab∑y=cd[gcd(x,y]=k],下界不是从1开始好像有点麻烦?可以容斥一下:设solve(a,b)函数解决的是: ∑ x = 1 a ∑ y = 1 b [ g c d ( x , y ] = k ] \sum_{x = 1}^a\sum_{y = 1}^b [gcd(x,y] = k] ∑x=1a∑y=1b[gcd(x,y]=k],答案就是 s o l v e ( b , d ) − s o l v e ( a − 1 , d ) − s o l v e ( b , c − 1 ) + s o l v e ( a − 1 , c − 1 ) solve(b,d) - solve(a - 1,d) - solve(b,c - 1) + solve(a - 1,c - 1) solve(b,d)−solve(a−1,d)−solve(b,c−1)+solve(a−1,c−1)
考虑
s
o
l
v
e
(
a
,
b
)
solve(a,b)
solve(a,b)怎么求:
s
o
l
v
e
(
a
,
b
)
=
∑
x
=
1
a
∑
y
=
1
b
[
g
c
d
(
x
,
y
]
=
k
]
=
∑
x
=
1
⌊
a
k
⌋
∑
y
=
1
⌊
b
k
⌋
[
g
c
d
(
x
,
y
]
=
1
]
=
∑
x
=
1
⌊
a
k
⌋
∑
y
=
1
⌊
b
k
⌋
∑
d
∣
g
c
d
(
x
,
y
)
μ
(
d
)
solve(a,b) = \sum_{x = 1}^a\sum_{y = 1}^b [gcd(x,y] = k]=\sum_{x = 1}^{\lfloor\frac{a}{k}\rfloor}\sum_{y = 1}^{\lfloor\frac{b}{k}\rfloor} [gcd(x,y] = 1]=\sum_{x = 1}^{\lfloor\frac{a}{k}\rfloor}\sum_{y = 1}^{\lfloor\frac{b}{k}\rfloor}\sum_{d | gcd(x,y)}\mu(d)
solve(a,b)=x=1∑ay=1∑b[gcd(x,y]=k]=x=1∑⌊ka⌋y=1∑⌊kb⌋[gcd(x,y]=1]=x=1∑⌊ka⌋y=1∑⌊kb⌋d∣gcd(x,y)∑μ(d)
改变一下枚举项,把d提前:
∑
d
=
1
⌊
a
k
⌋
μ
(
d
)
∑
x
=
1
⌊
a
k
∗
d
⌋
∑
y
=
1
⌊
b
k
∗
d
⌋
=
∑
d
=
1
⌊
a
k
⌋
μ
(
d
)
∗
⌊
a
k
∗
d
⌋
∗
⌊
b
k
∗
d
⌋
\sum_{d = 1}^{\lfloor\frac{a}{k}\rfloor}\mu(d)\sum_{x = 1}^{\lfloor\frac{a}{k * d}\rfloor}\sum_{y = 1}^{\lfloor\frac{b}{k * d}\rfloor} = \sum_{d = 1}^{\lfloor\frac{a}{k}\rfloor}\mu(d)*{\lfloor\frac{a}{k * d}\rfloor}*{\lfloor\frac{b}{k * d}\rfloor}
d=1∑⌊ka⌋μ(d)x=1∑⌊k∗da⌋y=1∑⌊k∗db⌋=d=1∑⌊ka⌋μ(d)∗⌊k∗da⌋∗⌊k∗db⌋
预处理
μ
(
x
)
\mu(x)
μ(x)的前缀和就可以直接分块,在
O
(
n
)
O(\sqrt n)
O(n)时间内完成
s
o
l
v
e
(
a
,
b
)
solve(a,b)
solve(a,b)的运算,总时间复杂度为
O
(
n
∗
n
)
O(n * \sqrt n)
O(n∗n)
代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 10;
typedef long long ll;
int t,a,b,c,d,k;
bool ispri[maxn];
int pri[maxn],mu[maxn];
void sieve(int n) {
ispri[0] = ispri[1] = true;
pri[0] = 0;
mu[1] = 1;
for(int i = 2; i <= n; i++) {
if(!ispri[i]) pri[++pri[0]] = i,mu[i] = -1;
for(int j = 1; j <= pri[0] && i * pri[j] <= n; j++) {
ispri[i * pri[j]] = true;
if(i % pri[j] == 0) break;
mu[i * pri[j]] = -mu[i];
}
}
for(int i = 1; i <= n; i++)
mu[i] += mu[i - 1];
}
ll solve(int n,int m) {
if(n > m) swap(n,m);
n /= k;m /= k;
ll ans = 0;
int i,j;
for(i = 1; i <= n; i = j + 1) {
j = min(n / (n / i),m / (m / i));
ans += 1ll * (n / i) * (m / i) * (mu[j] - mu[i - 1]);
}
return ans;
}
int main() {
sieve(50000);
scanf("%d",&t);
while(t--) {
ll res = 0;
scanf("%d%d%d%d%d",&a,&b,&c,&d,&k);
res = solve(b,d) - solve(a - 1,d) - solve(b,c - 1) + solve(a - 1,c - 1);
printf("%lld\n",res);
}
}