BZOJ4805: 欧拉函数求和(杜教筛)
程序员文章站
2022-09-10 23:33:00
4805: 欧拉函数求和 Description 给出一个数字N,求sigma(phi(i)),1<=i<=N 给出一个数字N,求sigma(phi(i)),1<=i<=N Input 正整数N。N<=2*10^9 正整数N。N<=2*10^9 Output 输出答案。 输出答案。 Sample I ......
4805: 欧拉函数求和
Time Limit: 15 Sec Memory Limit: 256 MBSubmit: 614 Solved: 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
直接大力杜教筛
$\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=5000030; int N,limit=5000000,tot=0,vis[MAXN],prime[MAXN]; LL phi[MAXN]; gp_hash_table<int,LL>Aphi; void GetPhi() { vis[1]=1;phi[1]=1; for(int i=1;i<=limit;i++) { if(!vis[i]) prime[++tot]=i,phi[i]=i-1; for(int j=1;j<=tot&&i*prime[j]<=limit;j++) { vis[i*prime[j]]=1; if(i%prime[j]==0) {phi[i*prime[j]]=phi[i]*prime[j];break;} else phi[i*prime[j]]=phi[i]*(prime[j]-1); } } for(int i=1;i<=limit;i++) phi[i]+=phi[i-1]; } LL SolvePhi(LL n) { if(n<=limit) return phi[n]; if(Aphi[n]) return Aphi[n]; LL tmp=n*(n+1)/2; for(int i=2,nxt;i<=n;i=nxt+1) { nxt=min(n,n/(n/i)); tmp-=SolvePhi(n/i)*(LL)(nxt-i+1); } return Aphi[n]=tmp; } int main() { GetPhi(); scanf("%lld",&N); printf("%lld",SolvePhi(N)); return 0; }