0%

YY的GCD 题解

YY的GCD 题解

$gcd(x,y) = k(k \in prime)$

$gcd(x/k,y/k) = 1$

正如某位大佬所说,此时应该直接上反演结论:

$\sum_{i=1}^n\sum_{j=1}^mgcd(\frac{i}{k},\frac{j}{k}) = 1 \iff \sum_{i=1}^{\frac{n}{k}}\sum_{j=1}^{\frac{m}{k}}\sum_{d|gcd(i,j)}\mu(d)$。

发现,这个式子实际上就是求对于固定的$d$,所有为$d$的倍数的对数之和,于是可以把$d$挪出来:

$\sum_{d=1}^{min(n/k,m/k)}\mu(d)\lfloor n/dk\rfloor \lfloor m/dk\rfloor$。

这样,我们就得到了对于单个质数$k$的对数之和。但是,这样做的复杂度约为$O(n\sqrt n)$,无法通过。

利用题解区说的套路,设$t=dk$,则:

$\sum_{k \in prime} \sum_{d=1}^{min(n/k,m/k)}\mu(t/k)\lfloor n/t\rfloor \lfloor m/t \rfloor \iff \sum_{t=1}^{min(n,m)} \sum_{k \in prime, k|t}\mu(t/k)\lfloor n/t\rfloor \lfloor m/t\rfloor \iff \sum_{t=1}^{min(n,m)}\lfloor n/t \rfloor \lfloor m/t \rfloor \sum_{k \in prime, k|t}\mu(t/k)$

这个$\sum_{k\in prime, k|t}\mu(t/k)$是可以预处理出来的,我们可以像埃氏筛一样把$k$的倍数都加一下。

预处理的复杂度接近$O(n)$,每次询问,我们只用把前面的用数论分块算出来,乘上后面的和就行了,时间复杂度为$O(\sqrt n)$。

总时间复杂度为$O(n+T\sqrt n)$。

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include<bits/stdc++.h>
using namespace std;
const int N = 2e7+10;
int t,n,m,vis[N],pri[N],tot,mu[N];
long long sum[N];
void pre(){
mu[1] = 1;
int lim = 1e7+10;
for (int i=2;i<=lim;i++){
if (!vis[i]){
vis[i] = i;
pri[++tot] = i;
mu[i] = -1;
}
for (int j=1;j<=tot;j++){
if (vis[i]<pri[j] || 1ll*i*pri[j]>lim) break;
vis[i*pri[j]] = pri[j];
if (vis[i]!=pri[j]) mu[i*pri[j]] = -mu[i];
}
}
for (int i=1;i<=tot;i++){
for (int j=1;j*pri[i]<=lim;j++){
sum[j*pri[i]]+=mu[j];
}
}
for (int i=1;i<=lim;i++) sum[i]+=sum[i-1];
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
pre();
cin>>t;
while (t--){
cin>>n>>m;
int r,Min = min(n,m);
long long ans = 0;
for (int l=1;l<=Min;l = r+1){
r = min(n/(n/l),m/(m/l));
ans+=(sum[r]-sum[l-1])*(n/l)*(m/l);
}
cout<<ans<<"\n";
}
return 0;
}