Link:http://acm.hdu.edu.cn/showproblem.php?pid=2824
The Euler function
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3889 Accepted Submission(s): 1613
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
Sample Output
Source
2009 Multi-University Training Contest 1 - Host by TJU
大概:求a~b段欧拉值和,要用到筛法欧拉函数。
筛选:1)如果n为素数,φ(n)=n-1;
2)如果m,n互质,φ(n*m)=φ(n)*φ(m);
核心就是当m%p==0:
f(m*p) = f(m) * p;//因为(p-1)是在f(m)中所以是乘p;
否则:
f(m*p) = f(m) * (p-1);
因为Euler函数是积性函数所以

综合上面两个式子就可以知道核心的推导公式如何得来
- #include<iostream>
- #include<cstdio>
- #include<ctime>
- using namespace std;
- typedef __int64 INT;
- #define N 3000001
- int prime[216818],phi[N];
- bool a[N];
- void is_prime()
- {
- int i,j,k;
- k=0;
- for(i=2;i<N;i++)
- {
- if(!a[i])
- {
- prime[k++]=i;
- phi[i]=i-1;
- }
- for(j=0;j<k&&i*prime[j]<N;j++)
- {
- a[prime[j]*i]=1;
- if(i%prime[j])
- phi[i*prime[j]]=phi[i]*(prime[j]-1);
- else
- {
- phi[i*prime[j]]=phi[i]*prime[j];
- break;
- }
-
- }
-
- }
- }
- int main()
- {
-
-
- int a,b,i;
- INT sum;
- is_prime();
- while(cin>>a>>b)
- {
- sum=0;
- for(i=a;i<=b;i++)
- sum+=phi[i];
- printf("%I64d\n",sum);
-
- }
-
- return 0;
- }