# 【BZOJ3930】选数（莫比乌斯反演，杜教筛）

## 题解

$f(i)$表示$gcd$恰好为$i$的方案数

$g(x)=\sum_{d|x}f(d)$

$f(1)=\sum_{i=1}\mu(i)g(i)$

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<set>
#include<map>
#include<vector>
#include<queue>
using namespace std;
#define MOD 1000000007
#define MAX 10000000
inline int read()
{
int x=0,t=1;char ch=getchar();
while((ch<'0'||ch>'9')&&ch!='-')ch=getchar();
if(ch=='-')t=-1,ch=getchar();
while(ch<='9'&&ch>='0')x=x*10+ch-48,ch=getchar();
return x*t;
}
int n,K,L,R;
bool zs[MAX];
int pri[MAX+1],tot,mu[MAX+1];
void pre()
{
zs[1]=true;mu[1]=1;
for(int i=2;i<=MAX;++i)
{
if(!zs[i])pri[++tot]=i,mu[i]=-1;
for(int j=1;j<=tot&&i*pri[j]<=MAX;++j)
{
zs[i*pri[j]]=true;
if(i%pri[j])mu[i*pri[j]]=-mu[i];
else break;
}
}
}
int fpow(int a,int b)
{
int s=1;
while(b){if(b&1)s=1ll*s*a%MOD;a=1ll*a*a%MOD;b>>=1;}
return s;
}
int G(int x,int L,int R)
{
L=(L-1)/x;R=R/x;
return fpow(R-L,n);
}
int main()
{
pre();
n=read();K=read();L=read();R=read();
int ans=0;
for(int i=K;i<=R;i+=K)
ans+=mu[i/K]*G(i,L,R)%MOD,ans%=MOD;
printf("%d\n",(ans+MOD)%MOD);
return 0;
}



$S(n)=\sum_{i=1}^n\mu(i)$

$g(1)S(n)=\sum_{i=1}^n(g*\mu)(i)-\sum_{i=2}^{n}g(i)S(\frac{n}{i})$

$g(x)=1$

$S(n)=1-\sum_{i=2}^nS(\frac{n}{i})$

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<set>
#include<map>
#include<vector>
#include<queue>
using namespace std;
#define MOD 1000000007
#define MAX 10000000
inline int read()
{
int x=0,t=1;char ch=getchar();
while((ch<'0'||ch>'9')&&ch!='-')ch=getchar();
if(ch=='-')t=-1,ch=getchar();
while(ch<='9'&&ch>='0')x=x*10+ch-48,ch=getchar();
return x*t;
}
int n,K,L,R;
bool zs[MAX];
int pri[MAX+1],tot,mu[MAX+1],smu[MAX+1];
map<int,int> M;
void pre()
{
zs[1]=true;mu[1]=1;
for(int i=2;i<=MAX;++i)
{
if(!zs[i])pri[++tot]=i,mu[i]=-1;
for(int j=1;j<=tot&&i*pri[j]<=MAX;++j)
{
zs[i*pri[j]]=true;
if(i%pri[j])mu[i*pri[j]]=-mu[i];
else break;
}
}
for(int i=1;i<=MAX;++i)smu[i]=smu[i-1]+mu[i];
}
int fpow(int a,int b)
{
int s=1;
while(b){if(b&1)s=1ll*s*a%MOD;a=1ll*a*a%MOD;b>>=1;}
return s;
}
int SMu(int x)
{
if(x<=MAX)return smu[x];
if(M[x])return M[x];
int ret=1;
for(int i=2,j;i<=x;i=j+1)
{
j=x/(x/i);
ret-=(j-i+1)*SMu(x/i);
}
return M[x]=ret;
}
int main()
{
pre();
n=read();K=read();L=read();R=read();
L=(L-1)/K;R/=K;
int ans=0;
for(int i=1,j;i<=R;i=j+1)
{
j=R/(R/i);if(i<=L)j=min(j,L/(L/i));
ans+=(SMu(j)-SMu(i-1))*fpow(R/i-L/i,n)%MOD;
ans%=MOD;
}
printf("%d\n",(ans+MOD)%MOD);
return 0;
}


posted @ 2018-01-17 16:53  小蒟蒻yyb  阅读(495)  评论(4编辑  收藏  举报