【模板】杜教筛(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\n",getphi(n),getmu(n));
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/acm1ruoji/p/10822561.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值