P2522 [HAOI2011]Problem b

Description

题目链接:P2522

有 $T$ 组数据,求

$$\sum\limits_{i=x}^n\sum\limits_{j=y}^m[gcd(i,j)=k]$$

$1\leq T,x,y,n,m,k\leq 5\times 10 ^4$。

Solution

可以根据容斥原理,原式可以分成四个子问题,每个子问题的式子为:

$$\sum\limits_{i=1}^n\sum\limits_{j=1}^m[gcd(i,j)=k]$$

考虑化简:

$$\sum\limits_{i=1}^{\lfloor\frac{n}{k}\rfloor}\sum\limits_{j=1}^{\lfloor \frac{m}{k}\rfloor}[gcd(i,j)=1]$$

根据莫比乌斯函数性质,将函数展开可以得到:

$$\sum\limits_{i=1}^{\lfloor\frac{n}{k}\rfloor}\sum\limits_{j=1}^{\lfloor \frac{m}{k}\rfloor}\sum\limits_{dgcd(i,j)}\mu(d)$$

变换求和顺序,先枚举 $dgcd(i,j)$,可以得到:

$$\sum\limits_{d=1}\mu(d)\sum\limits_{i=1}^{\lfloor\frac{n}{k}\rfloor}[di]\sum\limits_{j=1}^{\lfloor \frac{m}{k}\rfloor}[dj]$$

易知 $1 \sim \lfloor\frac{n}{k}\rfloor$ 中 $d$ 的倍数有 $\lfloor \frac{n}{kd} \rfloor$ 个,故原式化为:

$$\sum\limits_{d=1}\mu(d) \lfloor \frac{n}{kd} \rfloor\lfloor\frac{m}{kd} \rfloor$$

然后直接用数论分块求解即可。

时间复杂度:$\mathcal{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
#include<bits/stdc++.h>
#define Tp template<typename Ty>
#define Ts template<typename Ty,typename... Ar>
#define W while
#define I inline
#define RI register int
#define LL long long
#define Cn const
#define CI Cn int&
#define gc getchar
#define D isdigit(c=gc())
#define pc(c) putchar((c))
#define min(x,y) ((x)<(y)?(x):(y))
#define max(x,y) ((x)>(y)?(x):(y))
using namespace std;
namespace Debug{
Tp I void _debug(Cn char* f,Ty t){cerr<<f<<'='<<t<<endl;}
Ts I void _debug(Cn char* f,Ty x,Ar... y){W(*f!=',') cerr<<*f++;cerr<<'='<<x<<",";_debug(f+1,y...);}
Tp ostream& operator<<(ostream& os,Cn vector<Ty>& V){os<<"[";for(Cn auto& vv:V) os<<vv<<",";os<<"]";return os;}
#define gdb(...) _debug(#__VA_ARGS__,__VA_ARGS__)
}using namespace Debug;
namespace FastIO{
Tp I void read(Ty& x){char c;int f=1;x=0;W(!D) f=c^'-'?1:-1;W(x=(x<<3)+(x<<1)+(c&15),D);x*=f;}
Ts I void read(Ty& x,Ar&... y){read(x),read(y...);}
Tp I void write(Ty x){x<0&&(pc('-'),x=-x,0),x<10?(pc(x+'0'),0):(write(x/10),pc(x%10+'0'),0);}
Tp I void writeln(Cn Ty& x){write(x),pc('\n');}
}using namespace FastIO;
Cn int N=5e4+10;
int T,a,b,c,d,k,p[N],v[N],mu[N],tot;
I void GM(){
RI i,j;for(mu[1]=1,i=2;i<N;i++) for(!v[i]&&(mu[p[++tot]=i]=-1,0),j=1;j<=tot&&i*p[j]<N;j++)
if(v[i*p[j]]=1,i%p[j]) mu[i*p[j]]=-mu[i];else break ;
for(i=1;i<N;i++) mu[i]+=mu[i-1];
}
I int S(CI n,CI m){
RI i,j,X=0;for(i=1;i<=min(n,m);i=j+1) j=min(n/(n/i),m/(m/i)),X+=(mu[j]-mu[i-1])*(n/i)*(m/i);return X;
}
int main(){
GM(),read(T);W(T--) read(a,b,c,d,k),writeln(S(b/k,d/k)-S(b/k,(c-1)/k)-S((a-1)/k,d/k)+S((a-1)/k,(c-1)/k));return 0;
}