杜教筛
根据杜教筛的结论将两个函数分别代入:
μ(i):
μ
(
i
)
:
g(1)S(n)=∑i=1n(g∗μ)(i)−∑i=2ng(i)S(ni)
g
(
1
)
S
(
n
)
=
∑
i
=
1
n
(
g
∗
μ
)
(
i
)
−
∑
i
=
2
n
g
(
i
)
S
(
n
i
)
而 ∑d|nμ(d)=e ∑ d | n μ ( d ) = e
取 g(x)=1 g ( x ) = 1
则
S(n)=1−∑i=2nS(ni)
S
(
n
)
=
1
−
∑
i
=
2
n
S
(
n
i
)
φ(i):
φ
(
i
)
:
g(1)S(n)=∑i=1n(g∗μ)(i)−∑i=2ng(i)S(ni)
g
(
1
)
S
(
n
)
=
∑
i
=
1
n
(
g
∗
μ
)
(
i
)
−
∑
i
=
2
n
g
(
i
)
S
(
n
i
)
而 ∑d|nφ(d)=n ∑ d | n φ ( d ) = n
取 g(x)=x g ( x ) = x
则
S(n)=n(n+1)2−∑i=2niS(ni)
S
(
n
)
=
n
(
n
+
1
)
2
−
∑
i
=
2
n
i
S
(
n
i
)
分别递归算就好了。
BZOJ这道题丧病卡常,我找了学长的Blog卡了很久。。。
代码:
#include<cctype>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 4500005
#define K 100005
using namespace std;
typedef long long LL;
typedef unsigned int uint;
uint n,s,t,p[N];
LL mu[N],phi[N],P[K],M[K];
bool f[N],fp[K],fm[K];
inline char readc(){
static char buf[100000],*l=buf,*r=buf;
if (l==r) r=(l=buf)+fread(buf,1,100000,stdin);
if (l==r) return EOF; return *l++;
}
inline LL _read(){
LL x=0,f=1; char ch=readc();
while (!isdigit(ch)) { if (ch=='-') f=-1; ch=readc(); }
while (isdigit(ch)) x=(x<<3)+(x<<1)+(ch^48),ch=readc();
return x*f;
}
inline void Make(){
mu[1]=phi[1]=1;
for (uint i=2;i<N;i++){
if (!f[i]) p[++s]=i,mu[i]=-1,phi[i]=i-1;
for (uint j=1,v;j<=s&&i*p[j]<N;j++){
f[v=i*p[j]]=true;
if (!(i%p[j])){ mu[v]=0,phi[v]=phi[i]*p[j]; break; }
mu[v]=-mu[i],phi[v]=phi[i]*phi[p[j]];
}
}
for (uint i=2;i<N;i++) mu[i]+=mu[i-1],phi[i]+=phi[i-1];
}
LL PHI(uint x){
if (x<N) return phi[x];
LL ans=0,a=n/x;
if (fp[a]) return P[a];
for (uint l=2,r;l<=x;l=r+1)
r=x/(x/l),ans+=(r-l+1)*PHI(x/l);
return fp[a]=true,P[a]=1ll*x*(x+1)/2-ans;
}
LL MU(uint x){
if (x<N) return mu[x];
LL ans=0,a=n/x;
if (fm[a]) return M[a];
for (uint l=2,r;l<=x;l=r+1)
r=x/(x/l),ans+=(r-l+1)*MU(x/l);
return fm[a]=true,M[a]=1-ans;
}
int main(){
t=_read(),Make();
while (t--){
n=_read();
memset(fm,false,sizeof(fm));
memset(fp,false,sizeof(fp));
printf("%lld %lld\n",PHI(n),MU(n));
}
return 0;
}