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

4805: 欧拉函数求和

Time Limit:15 SecMemory Limit:256 MB
Submit:614Solved:342
[Submit][Status][Discuss]

Description

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

Input

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

Output

输出答案。

Sample Input

10

Sample Output

32

HINT

Source

By FancyCoder

直接大力杜教筛

$\sum_{i=1}^{n}\varphi(i) = \frac{n\times(n+1)}{2} - \sum_{d=2}^{n}\sum_{i=1}^{\lfloor\frac{n}{d}\rfloor}\varphi(i)$

#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=;
int N,limit=,tot=,vis[MAXN],prime[MAXN];
LL phi[MAXN];
gp_hash_table<int,LL>Aphi;
void GetPhi()
{
    vis[]=;phi[]=;
    for(int i=;i<=limit;i++)
    {
        if(!vis[i]) prime[++tot]=i,phi[i]=i-;
        for(int j=;j<=tot&&i*prime[j]<=limit;j++)
        {
            vis[i*prime[j]]=;
            if(i%prime[j]==) {phi[i*prime[j]]=phi[i]*prime[j];break;}
            else phi[i*prime[j]]=phi[i]*(prime[j]-);
        }
    }
    for(int i=;i<=limit;i++) phi[i]+=phi[i-];
}
LL SolvePhi(LL n)
{
    if(n<=limit) return phi[n];
    if(Aphi[n]) return Aphi[n];
    LL tmp=n*(n+)/;
    for(int i=,nxt;i<=n;i=nxt+)
    {
        nxt=min(n,n/(n/i));
        tmp-=SolvePhi(n/i)*(LL)(nxt-i+);
    }
    return Aphi[n]=tmp;
}
int main()
{
    GetPhi();
    scanf("%lld",&N);
    printf("%lld",SolvePhi(N));
    return ;
}

相关推荐