hdu 2824 The Euler function(欧拉函数)

来源:互联网 发布:不以 乎 句式 编辑:程序博客网 时间:2024/05/21 08:45

The Euler function

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 6640    Accepted Submission(s): 2775


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
2009 Multi-University Training Contest 1 - Host by TJU
 

题意:(a)是与a互质且小于a的值的个数。

定义:对于正整数n,φ(n)是小于或等于n的正整数中,与n互质的数的数目。
    例如:φ(8)=4,因为1,3,5,7均和8互质。
性质:1.若p是质数,φ(p)= p-1.
   2.若n是质数p的k次幂,φ(n)=(p-1)*p^(k-1)。因为除了p的倍数都与n互质
   3.欧拉函数是积性函数,若m,n互质,φ(mn)= φ(m)φ(n).

在程序中利用欧拉函数如下性质,可以快速求出欧拉函数的值(a为N的质因素)

  若( N%a ==0&&(N/a)%a ==0)则有:E(N)= E(N/a)*a;
  若( N%a ==0&&(N/a)%a !=0)则有:E(N)= E(N/a)*(a-1);

#include<cstdio>#include <algorithm>  #include <cstring> #define LL long long#define N 3000010using namespace std;int a,b;int phi[N],prime[N],fprime[N];  //fprime是标记函数,fprime[i]为0时说明i为质数。prime为质数数组,用以保存质数void Get(){int ans,k=0;memset(fprime,0,sizeof(fprime));for(int i=2;i<N;i++){if(fprime[i]==0){prime[k++]=i;phi[i]=i-1;}for(int j=0;j<k&&i*prime[j]<N;j++){fprime[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(){Get();while(~scanf("%d%d",&a,&b)){LL sum=0;for(int i=a;i<=b;i++)   sum+=phi[i];printf("%lld\n",sum);} return 0;}


0 0
原创粉丝点击