题目
给定 n n n, m m m,求 1 ≤ x ≤ n 1\leq x\leq n 1≤x≤n, 1 ≤ y ≤ m 1\leq y\leq m 1≤y≤m且 g c d ( x , y ) gcd(x, y) gcd(x,y)为质数的 ( x , y ) (x, y) (x,y)有多少对
分析
f
(
d
)
=
∑
i
=
1
n
∑
j
=
1
m
[
g
c
d
(
i
,
j
)
=
d
]
f(d)=\sum_{i=1}^{n}\sum_{j=1}^{m}[gcd(i,j)=d]
f(d)=i=1∑nj=1∑m[gcd(i,j)=d]
F
(
n
)
=
∑
n
∣
d
f
(
d
)
=
⌊
N
n
⌋
⌊
M
n
⌋
F(n)=\sum_{n|d}f(d)=\lfloor\frac{N}{n}\rfloor\lfloor\frac{M}{n}\rfloor
F(n)=n∣d∑f(d)=⌊nN⌋⌊nM⌋
A
n
s
=
∑
p
∈
p
r
i
m
e
f
(
p
)
Ans=\sum_{p\in prime}f(p)
Ans=p∈prime∑f(p)
经过莫比乌斯反演,变成了
A
n
s
=
∑
p
∈
p
r
i
m
e
∑
p
∣
d
μ
(
⌊
d
p
⌋
)
F
(
d
)
Ans=\sum_{p\in prime}\sum_{p|d}\mu(\lfloor\frac{d}{p}\rfloor)F(d)
Ans=p∈prime∑p∣d∑μ(⌊pd⌋)F(d)
最后
A
n
s
=
∑
T
=
1
m
i
n
(
n
,
m
)
⌊
n
T
⌋
⌊
m
T
⌋
(
∑
t
∣
T
μ
(
⌊
T
t
⌋
)
)
Ans=\sum_{T=1}^{min(n,m)}\lfloor\frac{n}{T}\rfloor\lfloor\frac{m}{T}\rfloor(\sum_{t|T}\mu(\lfloor\frac{T}{t}\rfloor))
Ans=T=1∑min(n,m)⌊Tn⌋⌊Tm⌋(t∣T∑μ(⌊tT⌋))
然后最终转换成这个式子可以发现
O
(
n
)
O(n)
O(n)的时间还是过不了,于是就要用到整除分块了,洛谷2261余数之和(一道比较基础的整除分块题)
余数之和题目链接
That‘s all
代码
#include <cstdio>
#include <vector>
#define N 10000001
#define min(a,b) ((a)<(b))?(a):(b)
#define rr register
using namespace std;
int mobius[N],v[N],now[N]; long long s[N];
inline int in(){
rr int ans=0; rr char c=getchar();
while (c<48||c>57) c=getchar();
while (c>47&&c<58) ans=(ans<<3)+(ans<<1)+c-48,c=getchar();
return ans;
}
void print(long long ans){
if (ans>9) print(ans/10);
putchar(ans%10+48);
}
signed main(){
mobius[1]=1; vector<int>prime;
for (rr int i=2;i<N;++i){//莫比乌斯函数
if (!v[i]) v[i]=i,mobius[i]=-1,prime.push_back(i);
for (rr int j=0;j<prime.size()&&i*prime[j]<N;++j){
v[i*prime[j]]=prime[j];
if (i%prime[j]) mobius[i*prime[j]]=-mobius[i]; else break;
}
}
for (rr int j=0;j<prime.size();++j)
for (rr int i=1;i*prime[j]<N;++i) now[i*prime[j]]+=mobius[i];//求每个数的约数的莫比乌斯前缀和
for (rr int i=1;i<N;++i) s[i]=s[i-1]+now[i];//前缀和
rr int t=in();
while (t--){
rr int n=in(),m=in();
if (n>m) n^=m,m^=n,n^=m;//交换
rr long long ans=0;
for (rr int l=1,r;l<=n;l=r+1){
r=min(n/(n/l),m/(m/l));//l到r为一个区间
ans+=1ll*(n/l)*(m/l)*(s[r]-s[l-1]);//整除分块
}
print(ans); putchar(10);
}
return 0;
}