【51nod 1239】 欧拉函数之和(杜教筛)

基准时间限制:3 秒 空间限制:131072 KB 分值: 320 难度:7级算法题
对正整数n,欧拉函数是小于或等于n的数中与n互质的数的数目。此函数以其首名研究者欧拉命名,它又称为Euler’s totient function、φ函数、欧拉商数等。例如:φ(8) = 4(Phi(8) = 4),因为1,3,5,7均和8互质。
S(n) = Phi(1) + Phi(2) + …… Phi(n),给出n,求S(n),例如:n = 5,S(n) = 1 + 1 + 2 + 2 + 4 = 10,定义Phi(1) = 1。由于结果很大,输出Mod 1000000007的结果。
Input
输入一个数N。(2 <= N <= 10^10)
Output
输出S(n) Mod 1000000007的结果。
Input示例
5
Output示例
10
上公式:

a n s ( n ) = n 2 + n 2 i = 2 n a n s ( n k )

然后就和上一题一样的套路了。
代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<map>
#include<algorithm>
#include<queue>
#include<cmath>
#define ll long long
using namespace std;
const int maxx=4700000;
const int mod=1000000007;
map<ll,ll> P;
bool isP[maxx];
int prime[maxx];
int cnt;
ll phi[maxx];
ll inv=500000004;
void init()
{
    phi[1]=1;
    for(int i=2;i<maxx;i++)
    {
        if(!isP[i]){prime[cnt++]=i;phi[i]=i-1;}
        for(int j=0;j<cnt&&(ll)i*prime[j]<maxx;j++)
        {
            isP[i*prime[j]]=true;
            if(i%prime[j])
                phi[i*prime[j]]=phi[i]*(prime[j]-1);
            else
            {
                phi[i*prime[j]]=phi[i]*prime[j];
                break;
            }
        }
    }
    for(int i=1;i<maxx;i++)
        phi[i]=(phi[i]+phi[i-1])%mod;
}
ll work(ll x)
{
    if(x<maxx)return phi[x];
    if(P[x])return P[x];
    ll ans=((x+1)%mod*(x%mod)%mod)*inv%mod;
    for(ll i=2,last;i<=x;i=last+1)
    {
        last=x/(x/i);
        ans=(ans-(last-i+1)*work(x/i)%mod)%mod;
    }
    ans=(ans+mod)%mod;
    P[x]=ans;
    return ans;
}
int main()
{
    //cout<<pow(1e10,2.0/3);
    //cout<<p(2,mod-2)<<endl;
    init();
    ll n;
    cin>>n;
    cout<<work(n)<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/coldfresh/article/details/81252764