f
(
n
,
m
)
=
∑
i
=
1
n
∑
j
=
1
m
(
g
c
d
(
i
,
j
)
=
=
k
)
=
∑
i
=
1
n
k
∑
j
=
1
m
k
(
g
c
d
(
i
,
j
)
=
=
1
)
=
∑
i
=
1
n
k
∑
j
=
1
m
k
∑
d
∣
i
,
d
∣
j
μ
(
d
)
=
∑
d
∣
i
,
d
∣
j
μ
(
d
)
∑
i
=
1
n
k
∑
j
=
1
m
k
=
∑
d
=
1
m
i
n
(
n
k
,
m
k
)
μ
(
d
)
∑
i
=
1
n
d
k
∑
j
=
1
m
d
k
=
∑
d
=
1
m
i
n
(
n
k
,
m
k
)
μ
(
d
)
⌊
n
d
k
⌋
∗
⌊
m
d
k
⌋
A
n
s
=
f
(
b
,
d
)
+
f
(
a
−
1
,
c
−
1
)
−
f
(
a
−
1
,
b
)
−
f
(
b
,
c
−
1
)
f(n,m)=\sum_{i=1}^n\sum_{j=1}^m(gcd(i,j)==k)\\=\sum_{i=1}^{\frac{n}{k}}\sum_{j=1}^{\frac{m}{k}}(gcd(i,j)==1)\\=\sum_{i=1}^{\frac{n}{k}}\sum_{j=1}^{\frac{m}{k}}\sum_{d|i,d|j}μ(d)\\=\sum_{d|i,d|j}μ(d)\sum_{i=1}^{\frac{n}{k}}\sum_{j=1}^{\frac{m}{k}}\\=\sum_{d=1}^{min(\frac{n}{k},\frac{m}{k})}μ(d)\sum_{i=1}^{\frac{n}{dk}}\sum_{j=1}^{\frac{m}{dk}}\\=\sum_{d=1}^{min(\frac{n}{k},\frac{m}{k})}μ(d)⌊\frac{n}{dk}⌋*⌊\frac{m}{dk}⌋\\Ans=f(b,d)+f(a-1,c-1)-f(a-1,b)-f(b,c-1)
f(n,m)=i=1∑nj=1∑m(gcd(i,j)==k)=i=1∑knj=1∑km(gcd(i,j)==1)=i=1∑knj=1∑kmd∣i,d∣j∑μ(d)=d∣i,d∣j∑μ(d)i=1∑knj=1∑km=d=1∑min(kn,km)μ(d)i=1∑dknj=1∑dkm=d=1∑min(kn,km)μ(d)⌊dkn⌋∗⌊dkm⌋Ans=f(b,d)+f(a−1,c−1)−f(a−1,b)−f(b,c−1)
由于直接计算
f
f
f时间复杂度仍然高,但是结合
μ
(
d
)
μ(d)
μ(d)的性质我们发现其实可以对
μ
(
d
)
μ(d)
μ(d)做一个前缀和优化一下。
void Mobius(){
......
}
LL GetAns(LL N,LL M,LL K){
LL I,Ans=0,Last;
N/=K,M/=K;
if(N>M){
swap(N,M);
}
for(I=1;I<=N;I=Last+1){
Last=min(N/(N/I),M/(M/I));
Ans+=(Miu[J]-Miu[I-1])*(N/I)*(M/I);
}
return Ans;
}
int main(){
LL I,J,K;
N=Read();Mobius();
for(I=1;I<=N;I++){
A=Read(),B=Read(),C=Read(),D=Read(),K=Read();
Ans=GetAns(B,D,K)-GetAns(A-1,D,K)-GetAns(B,C-1,K)+GetAns(A-1,C-1,K);
......
}
return 0;
}