BZOJ3944 Sum(洛谷P4213)

本文介绍了使用杜教筛解决BZOJ3944和洛谷P4213题目的过程。通过将杜教筛的两个函数应用于题目,实现了数论函数μ(i)和φ(i)的计算。由于BZOJ题目存在卡常问题,作者参考了学长的博客来优化算法,并分享了代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

杜教筛

BZOJ题目传送门
洛谷题目传送门

根据杜教筛的结论将两个函数分别代入:

μ(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)=1i=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)2i=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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值