UVA - 11426 欧拉函数

https://vjudge.net/problem/UVA-11426

O(n)求欧拉函数前缀和,O(sqrt(n))求每一个样例的结果

 

#include 
using namespace std;
#define ll long long
int n;

const int maxn = 4000000;
int phi[maxn+5];
int pri[maxn+5];
ll sum[maxn+5];
void get_phi()
{
    phi[1] = 1;
    for(int i = 2; i <= maxn; i++)
    {
        if (pri[i]==0)
        {
            pri[++pri[0]]=i;
            phi[i]=i-1;
        }
        for (int j=1;j<=pri[0] && pri[j]<=maxn/i;j++)
        {
            pri[pri[j]*i]=1;
            if (i%pri[j]==0)
            {
                phi[i*pri[j]]=phi[i]*pri[j];
                break;
            }
            else
            {
                phi[i*pri[j]]=phi[i]*(pri[j]-1);
            }
        }
    }
    for (int i=1;i<=maxn;i++)
    {
        sum[i]=sum[i-1]+phi[i];
    }
}


int main()
{
    get_phi();
    while (~scanf("%d",&n))
    {
        if (n==0) break;
        ll ans=0;
        int x=-1;
        for (int i=1;i<=n/i;i++)
		{
			ans+=i*sum[n/i];
			x=i;
		}
		for (int i=1;i<=n/i;i++)
		{
			ans+=(ll)sum[i]*(n/i+max(x,n/(i+1))+1)*(n/i-max(x,n/(i+1)))/2;
		}
        printf("%lld\n",ans-(ll)n*(n+1)/2);
    }
    return 0;
}

 

你可能感兴趣的:(ACM)