II.[CQOI2015]选数
我们要求这个东西:
\(\sum\limits_{a_1=L}^R\sum\limits_{a_2=L}^R\dots\sum\limits_{a_n=L}^R[\gcd\limits_{i=1}^n(a_i)=k]\)
老套路,除一下,得到
\(\sum\limits_{a_1=\left\lfloor\frac{L-1}{k}\right\rfloor}^{\left\lfloor\frac{R}{k}\right\rfloor}\sum\limits_{a_2=\left\lfloor\frac{L-1}{k}\right\rfloor}^{\left\lfloor\frac{R}{k}\right\rfloor}\dots\sum\limits_{a_n=\left\lfloor\frac{L-1}{k}\right\rfloor}^{\left\lfloor\frac{R}{k}\right\rfloor}[\gcd\limits_{i=1}^n(a_i)=1]\)
\(\mu\)一下,得到
\(\sum\limits_{a_1=\left\lfloor\frac{L-1}{k}\right\rfloor}^{\left\lfloor\frac{R}{k}\right\rfloor}\sum\limits_{a_2=\left\lfloor\frac{L-1}{k}\right\rfloor}^{\left\lfloor\frac{R}{k}\right\rfloor}\dots\sum\limits_{a_n=\left\lfloor\frac{L-1}{k}\right\rfloor}^{\left\lfloor\frac{R}{k}\right\rfloor}\sum\limits_{x|a_1,x|a_2,\dots,x|a_n}\mu(x)\)
把\(x\)拖出去,得到
\(\sum\limits_{x=1}^{\left\lfloor\frac{R}{k}\right\rfloor}\mu(x)(\left\lfloor\dfrac{L-1}{k}\right\rfloor-\left\lfloor\dfrac{R}{k}\right\rfloor)^n\)
后面的东西整除分块掉,前面的东西杜教筛掉。
然后就可以了。
复杂度\(O(\text{能过})\)。
代码:
#include<bits/stdc++.h>
using namespace std;
const int mod=1e9+7;
const int N=5000000;
int n,k,L,R,mu[N+10],pri[N+10],ans;
void getmu(){
mu[1]=1;
for(int i=2;i<=N;i++){
if(!pri[i])pri[++pri[0]]=i,mu[i]=-1;
for(int j=1;j<=pri[0]&&i*pri[j]<=N;j++){
pri[i*pri[j]]=true;
if(!(i%pri[j]))break;
mu[i*pri[j]]=-mu[i];
}
}
// for(int i=1;i<=10;i++)printf("%d\n",mu[i]);
for(int i=1;i<=N;i++)mu[i]=(0ll+mu[i]+mu[i-1]+mod)%mod;
// for(int i=1;i<=10;i++)printf("%d\n",mu[i]);
}
unordered_map<int,int>mp;
int djs(int x){
if(x<=N)return mu[x];
if(mp[x])return mp[x];
int res=1;
for(int l=2,r;l<=x;l=r+1)r=x/(x/l),res=(0ll+res-(1ll*(r-l+1)*djs(x/l)%mod)+mod)%mod;
return mp[x]=res;
}
int ksm(int x,int y){
int res=1;
for(;y;x=(1ll*x*x)%mod,y>>=1)if(y&1)res=(1ll*res*x)%mod;
return res;
}
int main(){
scanf("%d%d%d%d",&n,&k,&L,&R),L--,L/=k,R/=k,getmu();
// printf("%d %d\n",L,R);
for(int l=1,r;l<=R;l=r+1){
if(!(L/l))r=R/(R/l);
else r=min(L/(L/l),R/(R/l));
ans=(ans+(1ll*(djs(r)-djs(l-1)+mod)%mod*ksm((R/l)-(L/l),n)%mod))%mod;
}
printf("%d\n",ans);
return 0;
}