[杜教筛] BZOJ3944: Sum

题意

给定n, 求 ni=1ϕ(i) ni=1μ(i)
n2311

题解

假装做了一道新题
这道题=这题+这题

水啊水

#include
#include
#include
#include
#include  
using namespace std;
using namespace std::tr1; 
const int maxn=5000005, N=5000000; 
typedef long long LL;
int Q; 
int p[maxn],mu[maxn];
LL phi[maxn];
bool vis[maxn];
void Pre(){
    memset(vis,1,sizeof(vis));
    phi[1]=1; mu[1]=1;
    for(int i=2;i<=N;i++){
        if(vis[i]) p[++p[0]]=i, phi[i]=i-1, mu[i]=-1;
        for(int j=1;j<=p[0]&&p[j]*i<=N;j++){
            vis[p[j]*i]=false;
            if(i%p[j]==0){ phi[p[j]*i]=phi[i]*p[j]; mu[p[j]*i]=0; break; }
            phi[p[j]*i]=phi[i]*phi[p[j]]; mu[p[j]*i]=-mu[i];
        }
    } 
    for(int i=1;i<=N;i++) phi[i]+=phi[i-1], mu[i]+=mu[i-1];
}
unordered_map< LL, LL > lst_phi;
unordered_map< LL, int > lst_mu; 
LL Sum_phi(LL n){
    if(n<=N) return phi[n];
    if(lst_phi.find(n)!=lst_phi.end()) return lst_phi[n];
    LL res=n*(1+n)/2;
    for(LL i=2,nxt;i<=n;i=nxt+1){
        nxt=n/(n/i);
        res-=Sum_phi(n/i)*(nxt-i+1);
    }
    return lst_phi[n]=res;
}
int Sum_mu(LL n){
    if(n<=N) return mu[n];
    if(lst_mu.find(n)!=lst_mu.end()) return lst_mu[n];
    int res=1;
    for(LL i=2,nxt;i<=n;i=nxt+1){
        nxt=n/(n/i);
        res-=Sum_mu(n/i)*(nxt-i+1);
    }
    return lst_mu[n]=res;
}
int main(){
    freopen("bzoj3944.in","r",stdin);
    freopen("bzoj3944.out","w",stdout);
    Pre();
    scanf("%d",&Q);
    while(Q--){
        int n; scanf("%d",&n);
        printf("%lld %d\n",Sum_phi(n),Sum_mu(n));   
    }
    return 0;
}

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