bzoj 3944: Sum 杜教筛

题意

bzoj 3944: Sum 杜教筛_第1张图片

分析

直接用线性筛来求肯定不行,我们考虑别的方法。

ans2

S(n)=ni=1μ(i)

μd|iμ(d)=0(i>1)1(i=1)

ni=1d|iμ(d)=1

ni=1d|iμ(d)=ni=1d|iμ(d/i)=nd=1ndi=1μ(i)=nd=1S(nd)

S(n)=1nd=2S(nd)

[1,5000000]ϕμ5000000

ans1d|iϕ(d)=i 同理即可得到答案。

代码

#include
#include
#include
#include
#include
#include
#define LL long long
#define M 5000000
using namespace std;

LL mu[M+5],phi[M+5];
bool not_prime[M+5];
int prime[M],tot;
map <int,LL> w1,w2;

void prework(int n)
{
    mu[1]=phi[1]=1;
    for (int i=2;i<=n;i++)
    {
        if (!not_prime[i])
        {
            prime[++tot]=i;
            mu[i]=-1;
            phi[i]=i-1;
        }
        for (int j=1;j<=tot&&i*prime[j]<=n;j++)
        {
            not_prime[i*prime[j]]=1;
            if (i%prime[j]==0)
            {
                mu[i*prime[j]]=0;
                phi[i*prime[j]]=phi[i]*prime[j];
                break;
            }
            mu[i*prime[j]]=-mu[i];
            phi[i*prime[j]]=phi[i]*phi[prime[j]];
        }
    }
    for (int i=1;i<=n;i++)
    {
        phi[i]+=phi[i-1];
        mu[i]+=mu[i-1];
    }
}

LL get_phi(LL n)
{
    if(n<=M) return phi[n];
    if(w1.count(n)) return w1[n];
    LL ans=(LL)n*(n+1)/2;
    for (LL i=2,last;i<=n;i=last+1)
    {
        last=n/(n/i);
        ans-=(last-i+1)*get_phi(n/i);
    }
    w1[n]=ans;
    return ans;
}

LL get_mu(LL n)
{
    if(n<=M) return mu[n];
    if (w2.count(n)) return w2[n];
    LL ans=1;
    for (LL i=2,last;i<=n;i=last+1)
    {
        last=n/(n/i);
        ans-=(last-i+1)*get_mu(n/i);
    }
    w2[n]=ans;
    return ans;
}

int main()
{
    prework(M);
    int t;
    scanf("%d",&t);
    while (t--)
    {
        int n;
        scanf("%d",&n);
        printf("%lld ",get_phi(n));
        printf("%lld\n",get_mu(n));
    }
    return 0;
}

你可能感兴趣的:(杜教筛)