problem
给出 n n n,统计满足下面条件的数对 ( a , b ) (a,b) (a,b) 的个数:
- 1 ≤ a < b ≤ n 1\le a<b\le n 1≤a<b≤n;
- ( a + b ) ∣ a b (a+b)|ab (a+b)∣ab。
数据范围: n ≤ 2 31 − 1 n\le 2^{31}-1 n≤231−1。
solution
我们要算的是
a n s = ∑ a = 1 n ∑ b = a + 1 n [ ( a + b ) ∣ a b ] ans=\sum_{a=1}^n\sum_{b=a+1}^n[(a+b)|ab] ans=a=1∑nb=a+1∑n[(a+b)∣ab]
考虑 ( a + b ) ∣ a b (a+b)|ab (a+b)∣ab 什么情况下成立。设 gcd ( a , b ) = d \gcd(a,b)=d gcd(a,b)=d, a = u d a=ud a=ud, b = v d b=vd b=vd 的话,就是:
( u + v ) d ∣ u v d 2 ⇒ ( u + v ) ∣ u v d (u+v)d|uvd^2\Rightarrow (u+v)|uvd (u+v)d∣uvd2⇒(u+v)∣uvd
由于 gcd ( u , v ) = 1 \gcd(u,v)=1 gcd(u,v)=1,所以 gcd ( u + v , u v ) = 1 \gcd(u+v,uv)=1 gcd(u+v,uv)=1,那么就要满足:
( u + v ) ∣ d (u+v)|d (u+v)∣d
所以我们要求的其实是:
a n s = ∑ u = 1 n ∑ v = u + 1 n ∑ d = 1 ⌊ n v ⌋ [ ( u + v ) ∣ d ] [ gcd ( u , v ) = 1 ] ans=\sum_{u=1}^n\sum_{v=u+1}^n\sum_{d=1}^{\lfloor\frac n v\rfloor}[(u+v)|d][\gcd(u,v)=1] ans=u=1∑nv=u+1∑nd=1∑⌊vn⌋[(u+v)∣d][gcd(u,v)=1]
由于在 1 ∼ ⌊ n v ⌋ 1\sim\lfloor\frac n v\rfloor 1∼⌊vn⌋ 中,为 u + v u+v u+v 的倍数的有 ⌊ n v ( u + v ) ⌋ \lfloor\frac n {v(u+v)}\rfloor ⌊v(u+v)n⌋ 个,所以(上界我们先不予考虑):
a n s = ∑ u = 1 ∑ v = u + 1 ⌊ n v ( u + v ) ⌋ [ gcd ( u , v ) = 1 ] ans=\sum_{u=1}\sum_{v=u+1}\lfloor\frac n {v(u+v)}\rfloor[\gcd(u,v)=1] ans=u=1∑v=u+1∑⌊v(u+v)n⌋[gcd(u,v)=1]
然后可以反演一波:
a n s = ∑ u = 1 ∑ v = u + 1 ⌊ n v ( u + v ) ⌋ ∑ t ∣ u , t ∣ v μ ( t ) = ∑ t = 1 μ ( t ) ∑ u = 1 ∑ v = u + 1 ⌊ n v t ( u t + v t ) ⌋ = ∑ t = 1 μ ( t ) ∑ u = 1 ∑ v = u + 1 ⌊ n v ( u + v ) t 2 ⌋ \begin{aligned} ans&=\sum_{u=1}\sum_{v=u+1}\lfloor\frac n {v(u+v)}\rfloor\sum_{t|u,t|v}\mu(t)\\ &=\sum_{t=1}\mu(t)\sum_{u=1}\sum_{v=u+1}\lfloor\frac n {vt(ut+vt)}\rfloor\\ &=\sum_{t=1}\mu(t)\sum_{u=1}\sum_{v=u+1}\lfloor\frac n {v(u+v)t^2}\rfloor \end{aligned} ans=u=1∑v=u+1∑⌊v(u+v)n⌋t∣u,t∣v∑μ(t)=t=1∑μ(t)u=1∑v=u+1∑⌊vt(ut+vt)n⌋=t=1∑μ(t)u=1∑v=u+1∑⌊v(u+v)t2n⌋
然后设 k = u + v k=u+v k=u+v,由于 v > u v>u v>u,所以 v v v 的下界就是 ⌊ k 2 ⌋ + 1 \lfloor\frac k {2}\rfloor+1 ⌊2k⌋+1 了,即:
a n s = ∑ t = 1 μ ( t ) ∑ k = 1 ∑ v = ⌊ k 2 ⌋ + 1 ⌊ n v k t 2 ⌋ ans=\sum_{t=1}\mu(t)\sum_{k=1}\sum_{v=\lfloor\frac k {2}\rfloor+1}\lfloor\frac n {vkt^2}\rfloor ans=t=1∑μ(t)k=1∑v=⌊2k⌋+1∑⌊vkt2n⌋
讨论一下上界, t ≤ n t\le \sqrt n t≤n, k ≤ 2 n t k\le \frac{\sqrt{2n}}{t} k≤t2n, v ≤ k − 1 v\le k-1 v≤k−1,这里可以比准确上界超出一点,反正超出部分贡献为 0 0 0。
用积分估计复杂度为 O ( n 3 4 ) O(n^{\frac 3 4}) O(n43)。
code
#include<cmath>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 1000005
#define ll long long
using namespace std;
int n;
int sum,prime[N],mark[N],mu[N];
void linear_sieves(){
mu[1]=1;
for(int i=2;i<N;++i){
if(!mark[i]) prime[++sum]=i,mu[i]=-1;
for(int j=1;j<=sum&&i*prime[j]<N;++j){
mark[i*prime[j]]=1;
if(i%prime[j]==0) {mu[i*prime[j]]=0;break;}
mu[i*prime[j]]=-mu[i];
}
}
}
int main(){
scanf("%d",&n);
linear_sieves();
ll ans=0;
for(int d=1;(ll)d*d<=n;++d){
if(!mu[d]) continue;
int up=min((ll)n/d/d,(ll)sqrt(2ll*n)/d);
for(int k=1;k<=up;++k){
int T=n/d/d/k,u;
for(int v=k/2+1;v<=min(k-1,T);v=u+1){
u=min(k-1,T/(T/v));
ans+=(ll)mu[d]*(u-v+1)*(T/v);
}
}
}
printf("%lld\n",ans);
return 0;
}