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
就是求从a到b的欧拉函数之和;
解题思路:
欧拉函数:对于正整数n,欧拉函数Euler(n)是1到n-1中与n互质的数的个数,特别的,Euler(1) = 1,若n为质数则
有 Euler(n) = n - 1;
欧拉函数的基本性质:
① N是不为0的整数。φ(1)=1(唯一和1互质的数就是1本身)
② 除了N=2,φ(N)都是偶数.
③ 小于N且与N互质的所有数的和是φ(n)*n/2。
④ 欧拉函数是积性函数——若m,n互质,φ(m*n)=φ(m)*φ(n)。
⑤ 当N为奇数时,φ(2*N)=φ(N)
⑥ 若N是质数p的k次幂,φ(N)=p^k-p^(k-1)=(p-1)p^(k-1),因为除了p的倍数外,其他数都跟N互质。
⑦ 当N是质数时,φ(N) = N-1
这可以利用欧拉筛法(筛选素数表的一种方法)来解决;
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
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;//性质7
}
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];//性质4
}else
phi[i*prime[j]]=phi[i]*(prime[j]-1);//性质4
}
}
}
int main() {
long long sum;
int a,b;
get_phi();
while (~scanf("%d%d",&a,&b)) {
sum=0;
for (int i=a; i<=b; i++)
sum=sum+phi[i];
cout<<sum<<endl;
}
return 0;
}
看完之后,一定要关注我,互关!
推荐:给诸位看官推荐一首好歌《 一直很安静》(阿桑);