[51nod1239] 欧拉函数之和(杜教筛)

题面

传送门

题解

话说……就一个杜教筛……刚才那道拿过来改几行就行了……

//minamoto
#include<bits/stdc++.h>
#define R register
#define ll long long
#define IT map<ll,int>::iterator
#define fp(i,a,b) for(R int i=a,I=b+1;i<I;++i)
#define fd(i,a,b) for(R int i=a,I=b-1;i>I;--i)
#define go(u) for(int i=head[u],v=e[i].v;i;i=e[i].nx,v=e[i].v)
using namespace std;
const int N=5e6+5,P=1e9+7,inv2=500000004;
inline int add(R int x,R int y){return x+y>=P?x+y-P:x+y;}
inline int dec(R int x,R int y){return x-y<0?x-y+P:x-y;}
inline int mul(R int x,R int y){return 1ll*x*y-1ll*x*y/P*P;}
inline int calc(R int x){return (1ll*x*(x+1)>>1)%P;}
bitset<N>vis;int p[N],phi[N],m,sqr,res;ll n;map<ll,int>mp;IT it;
void init(int n){
	phi[1]=1;
	fp(i,2,n){
		if(!vis[i])p[++m]=i,phi[i]=i-1;
		for(R int j=1;j<=m&&1ll*i*p[j]<=n;++j){
			vis[i*p[j]]=1;
			if(i%p[j]==0){phi[i*p[j]]=phi[i]*p[j];break;}
			phi[i*p[j]]=phi[i]*(p[j]-1);
		}
	}
	fp(i,2,n)phi[i]=add(phi[i],phi[i-1]);
}
int Phi(ll n){
	if(n<=sqr)return phi[n];
	it=mp.find(n);
	if(it!=mp.end())return it->second;
	int res=calc(n%P);
	for(R ll i=2,j;i<=n;i=j+1)
		j=n/(n/i),res=dec(res,mul((j-i+1)%P,Phi(n/i)));
	return mp[n]=res;
}
int main(){
//	freopen("testdata.in","r",stdin);
	scanf("%lld",&n),init(sqr=N-5);
	printf("%d\n",Phi(n));
	return 0;
}
posted @ 2019-02-25 22:25  bztMinamoto  阅读(205)  评论(0编辑  收藏  举报
Live2D