【模板】杜教筛(Sum)

传送门:

#include <cstdio>
#include <cstdlib>
#include <string>
#include <cstring>
#include <cmath>
#include <tr1/unordered_map>
using namespace std;
#define ll long long
#define re register
const int N=6e6+10;
const int M=6e6;
void read(int &a)
{
    a=0;
    int d=1;
    char ch;
    while(ch=getchar(),!isdigit(ch))
        if(ch=='-')
            d=-1;
    a=ch^48;
    while(ch=getchar(),isdigit(ch))
        a=(a<<3)+(a<<1)+(ch^48);
    a*=d;
}
tr1::unordered_map <int,ll> ansphi;
tr1::unordered_map <int,int> ansmu;
ll phi[N],mu[N],pri[N];
bool vis[N];
int cnt;
inline void init()
{
    mu[1]=phi[1]=1;
    for(re int i=2;i<=M;i++)
    {
        if(!vis[i])
            phi[i]=i-1,pri[++cnt]=i,mu[i]=-1;
        for(re int j=1;j<=cnt&&pri[j]*i<=M;j++)
        {
            vis[i*pri[j]]=1;
            if(i%pri[j]==0)
            {
                phi[i*pri[j]]=phi[i]*pri[j];
                break;
            }
            mu[i*pri[j]]=-mu[i];
            phi[i*pri[j]]=phi[i]*(pri[j]-1);
        }
    }
    for(re int i=1;i<=M;i++)
        mu[i]+=mu[i-1],phi[i]+=phi[i-1];
}
inline ll getphi(int x)
{
    if(x<=M)
        return phi[x];
    if(ansphi[x])
        return ansphi[x];
    ll ans=1ll*(x+1)*x/2;
    for(int l=2,r;l<=x;l=r+1)
    {
        r=x/(x/l);
        ans-=(r-l+1)*getphi(x/l);
    }
    return ansphi[x]=ans;
}
inline int getmu(int x)
{
    if(x<=M)
        return mu[x];
    if(ansmu[x])
        return ansmu[x];
    ll ans=1;
    for(int l=2,r;l<=x;l=r+1)
    {
        r=x/(x/l);
        ans-=(r-l+1)*getmu(x/l);
    }
    return ansmu[x]=ans;
}
int main()
{
    init();
    int T;
    read(T);
    while(T--)
    {
        int n;
        read(n);
        printf("%lld %d
",getphi(n),getmu(n));
    }
    return 0;
}
原文地址:https://www.cnblogs.com/acm1ruoji/p/10822561.html