bzoj3944 Sum

题目

杜教筛第一题。

数学推导过程详见这里

具体实现的时候要用一个hash表或者map存一下,其实感觉两个东西差不多快。想要提高速度应该调一调M的大小,可以三分试一试呀。

#include<bits/stdc++.h>
#define ll long long 
#define M 4500000
using namespace std;
int prime[M+5],notp[M+5],cnt;
ll mu[M+5],phi[M+5],T,n;
map <int,ll> mpphi,mpmu;
inline char nc()
{
    static char buf[100000],*p1=buf,*p2=buf;
    return p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++;
}
inline ll read()
{
    ll x=0,b=1;
    char c=nc();
    for(;!(c<='9'&&c>='0');c=nc())if(c=='-')b=-1;
    for(;c<='9'&&c>='0';c=nc())x=x*10+c-'0';
    return x*b;
}
inline void init()
{
    notp[1]=true,mu[1]=1,phi[1]=1;
    for(int i=1;i<=M;i++)
    {
        if(!notp[i])prime[++cnt]=i,mu[i]=-1,phi[i]=i-1;
        for(int j=1;j<=cnt&&i*prime[j]<=M;j++)
        {
            notp[i*prime[j]]=true;
            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<=M;i++)phi[i]+=phi[i-1],mu[i]+=mu[i-1];
}
inline ll getphi(ll x)
{
    if(x<=M)return phi[x];
    if(mpphi[x])return mpphi[x];
    ll tmp;
    tmp=x*(x+1)/2;
    int lst;
    for(int i=2;i<=x;i=lst+1)
    {
        lst=x/(x/i);
        tmp-=getphi(x/i)*(ll)(lst-i+1);
        if(x==lst)break;
    }
    mpphi[x]=tmp;
    return tmp;
}
inline ll getmu(ll x)
{
    if(x<=M)return mu[x];
    if(mpmu[x])return mpmu[x];
    ll tmp;
    tmp=1;
    int lst;
    for(int i=2;i<=x;i=lst+1)
    {
        lst=x/(x/i);
        tmp-=getmu(x/i)*(ll)(lst-i+1);
        if(x==lst)break;
    }
    mpmu[x]=tmp;
    return tmp;
}
int main()
{
    freopen("in.txt","r",stdin);
    init();T=read();
    while(T--)
    {
        n=read();
        printf("%lld %lld\n",getphi(n),getmu(n));
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值