【刷题】BZOJ 4805 欧拉函数求和

Description

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

Input

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

Output

输出答案。

Sample Input

10

Sample Output

32

Solution

杜教筛裸题

#include<bits/stdc++.h>
#define ui unsigned int
#define ll long long
#define db double
#define ld long double
#define ull unsigned long long
const int MAXN=1000000+10;
int n,vis[MAXN],phi[MAXN],prime[MAXN],cnt;
ll s[MAXN];
std::map<int,ll> M;
template<typename T> inline void read(T &x)
{
	T data=0,w=1;
	char ch=0;
	while(ch!='-'&&(ch<'0'||ch>'9'))ch=getchar();
	if(ch=='-')w=-1,ch=getchar();
	while(ch>='0'&&ch<='9')data=((T)data<<3)+((T)data<<1)+(ch^'0'),ch=getchar();
	x=data*w;
}
template<typename T> inline void write(T x,char ch='\0')
{
	if(x<0)putchar('-'),x=-x;
	if(x>9)write(x/10);
	putchar(x%10+'0');
	if(ch!='\0')putchar(ch);
}
template<typename T> inline void chkmin(T &x,T y){x=(y<x?y:x);}
template<typename T> inline void chkmax(T &x,T y){x=(y>x?y:x);}
template<typename T> inline T min(T x,T y){return x<y?x:y;}
template<typename T> inline T max(T x,T y){return x>y?x:y;}
inline void init()
{
	memset(vis,1,sizeof(vis));
	vis[0]=vis[1]=0;
	phi[1]=1;
	for(register int i=2;i<MAXN;++i)
	{
		if(vis[i])
		{
			prime[++cnt]=i;
			phi[i]=i-1;
		}
		for(register int j=1;j<=cnt&&i*prime[j]<MAXN;++j)
		{
			vis[i*prime[j]]=0;
			if(i%prime[j])phi[i*prime[j]]=phi[i]*phi[prime[j]];
			else
			{
				phi[i*prime[j]]=phi[i]*prime[j];
				break;
			}
		}
	}
	for(register int i=1;i<MAXN;++i)s[i]=s[i-1]+phi[i];
}
inline ll S(int x)
{
	if(x<MAXN)return s[x];
	if(M[x])return M[x];
	ll res=0;
	for(register int i=2;;)
	{
		if(i>x)break;
		int j=x/(x/i);
		res+=1ll*(j-i+1)*S(x/i);
		i=j+1;
	}
	return M[x]=1ll*(x+1)*x/2-res;
}
int main()
{
	init();read(n);
	write(S(n),'\n');
	return 0;
}
posted @ 2018-08-30 21:14  HYJ_cnyali  阅读(154)  评论(0编辑  收藏  举报