BZOJ4805: 欧拉函数求和(杜教筛)

2018-04-10 16:03:30 浏览数 (1)

欧拉函数求和

Description

给出一个数字N,求sigma(phi(i)),1<=i<=N

Input

正整数N。N<=2*10^9

Output

输出答案。

Sample Input

10

Sample Output

32

HINT

直接大力杜教筛

sum_{i=1}^{n}varphi(i) = frac{ntimes(n 1)}{2} - sum_{d=2}^{n}sum_{i=1}^{lfloorfrac{n}{d}rfloor}varphi(i)

代码语言:javascript复制
#include<cstdio>
#include<map>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/hash_policy.hpp>
#define LL long long 
using namespace std;
using namespace __gnu_pbds;
const int MAXN=5000030;
int N,limit=5000000,tot=0,vis[MAXN],prime[MAXN];
LL phi[MAXN];
gp_hash_table<int,LL>Aphi;
void GetPhi()
{
    vis[1]=1;phi[1]=1;
    for(int i=1;i<=limit;i  )
    {
        if(!vis[i]) prime[  tot]=i,phi[i]=i-1;
        for(int j=1;j<=tot&&i*prime[j]<=limit;j  )
        {
            vis[i*prime[j]]=1;
            if(i%prime[j]==0) {phi[i*prime[j]]=phi[i]*prime[j];break;}
            else phi[i*prime[j]]=phi[i]*(prime[j]-1);
        }
    }
    for(int i=1;i<=limit;i  ) phi[i] =phi[i-1];
}
LL SolvePhi(LL n)
{
    if(n<=limit) return phi[n];
    if(Aphi[n]) return Aphi[n];
    LL tmp=n*(n 1)/2;
    for(int i=2,nxt;i<=n;i=nxt 1)
    {
        nxt=min(n,n/(n/i));
        tmp-=SolvePhi(n/i)*(LL)(nxt-i 1);
    }
    return Aphi[n]=tmp;
}
int main()
{
    GetPhi();
    scanf("%lld",&N);
    printf("%lld",SolvePhi(N));
    return 0;
}

0 人点赞