The Euler function
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 8389 Accepted Submission(s): 3516
Problem 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
Recommend
gaojie
求一个范围中欧拉函数的和,根据数据范围,用筛选法打表,复杂度O(nlogn)
代码如下:
#include <cstdio> #include <iostream> #include <algorithm> using namespace std; typedef long long LL; const int N=3000010; int prime[N],isprime[N]; int phi[N]; void get_phi() { int i,j,cnt=0; for(i=2;i<N;i++){ if(isprime[i]==0){ prime[cnt++]=i; phi[i]=i-1; } for(j=0;j<cnt&&i*prime[j]<N;j++){ isprime[i*prime[j]]=1; if(i%prime[j]==0) phi[i*prime[j]]=phi[i]*prime[j]; else phi[i*prime[j]]=phi[i]*(prime[j]-1); } } } int main() { ios::sync_with_stdio(false); int a,b; LL sum; get_phi(); while(cin>>a>>b) { sum=0; for(int i=a;i<=b;i++) sum+=phi[i]; cout<<sum<<endl; } return 0; }