HDU2824 The Euler function
Time Limit: 1000MS | Memory Limit: 32768KB | 64bit IO Format: %I64d & %I64u |
Description
The Euler function phi is an important kind of function in number theory, (n) represents the amount of the numbers which are smaller than n and coprime to n, and this function has a lot of beautiful characteristics. Here comes a very easy question: suppose you are given a, b, try to calculate (a)+ (a+1)+....+ (b)
Input
There are several test cases. Each line has two integers a, b (2<a<b<3000000).
Output
Output the result of (a)+ (a+1)+....+ (b)
Sample Input
3 100
Sample Output
3042
Source
2009 Multi-University Training Contest 1 - Host by TJU
算出300w个范围内的欧拉函数,然后求个前缀和。
然而这题内存限制好小,直接套惯用的模板会MLE。
已经没有什么优化的空间了,只好重构代码。
解1:MLE
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /*by SilverN*/ 2 #include<iostream> 3 #include<algorithm> 4 #include<cstring> 5 #include<cstdio> 6 #include<cmath> 7 #define LL long long 8 using namespace std; 9 const int mxn=3000002; 10 LL phi[mxn],pr[mxn>>1]; 11 int cnt=0; 12 int mark[mxn]; 13 int n; 14 void euler(){ 15 phi[1]=1; 16 for(int i=2;i<=mxn;i++){ 17 if(!mark[i]) 18 pr[++cnt]=mark[i]=i,phi[i]=i-1; 19 for(int j=1;j<=cnt && pr[j]*i<mxn;j++){ 20 mark[i*pr[j]]=pr[j]; 21 if(mark[i]==pr[j]){ 22 phi[pr[j]*i]=phi[i]*pr[j]; 23 break; 24 } 25 else phi[i*pr[j]]=phi[i]*(pr[j]-1); 26 } 27 } 28 return; 29 } 30 int main(){ 31 int s,t; 32 euler(); 33 int i; 34 for(i=1;i<=mxn;i++)phi[i]+=phi[i-1]; 35 while(scanf("%d%d",&s,&t)!=EOF)printf("%I64d\n",phi[t]-phi[s-1]); 36 return 0; 37 }
解2:AC
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <cstdio> 2 long long n=3000000,phi[3000001],p[1500001],top=0; 3 bool ma[3000001]; 4 void init() 5 { 6 phi[1]=1; 7 for (int i=2;i<=n;++i) 8 { 9 if (!ma[i]) ma[i]=true,p[++top]=i,phi[i]=i-1; 10 for (int j=1;j<=top&&i*p[j]<=n;++j) 11 { 12 ma[i*p[j]]=true; 13 if (i%p[j]==0){phi[i*p[j]]=phi[i]*p[j];break;} 14 else phi[i*p[j]]=(p[j]-1)*phi[i]; 15 } 16 } 17 } 18 int main() 19 { 20 int l,r; init(); 21 for (int i=1;i<=n;++i) phi[i]+=phi[i-1]; 22 while (~scanf("%d%d",&l,&r)) printf("%lld\n",phi[r]-phi[l-1]); 23 }
本文为博主原创文章,转载请注明出处。