HDU 2824.The Euler function-筛选法求欧拉函数

欧拉函数:

φ(n)=n*(1-1/p1)(1-1/p2)....(1-1/pk),其中p1、p2…pk为n的所有素因子。
比如:φ(12)=12*(1-1/2)(1-1/3)=4。
可以用类似求素数的筛法。(素数打表)
先筛出n以内的所有素数,再以素数筛每个数的φ值。
比如求10以内所有数的φ值:
设一数组phi[11],赋初值phi[1]=1,phi[2]=2...phi[10]=10;
然后从2开始循环,把2的倍数的φ值*(1-1/2),则phi[2]=2*1/2=1,phi[4]=4*1/2=2,phi[6]=6*1/2=3....;
再是3,3的倍数的φ值*(1-1/3),则phi[3]=3*2/3=2,phi[6]=3*2/3=2,phi[9]=.....;(4的时候不符合条件)
再5,再7...因为对每个素数都进行如此操作,因此任何一个n都得到了φ(n)=n*(1-1/p1)(1-1/p2)....(1-1/pk)的运算。

传送门:http://blog.csdn.net/scnujack/article/details/7420816

 

The Euler function

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

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
 
 
 
代码:
 1 #include<bits/stdc++.h>
 2 const int maxn=3*1e6+10;
 3 using namespace std;
 4 typedef long long ll;
 5 ll phi[maxn];
 6 void euler(){
 7     for(int i=1;i<maxn;i++)
 8         phi[i]=i;
 9     for(int i=2;i<maxn;i++){
10         if(i==phi[i]){                     //此时,i为素数,举例4,因为2的时候phi[4]值发生变化了,所以就把4跳过去了
11             for(int j=i;j<maxn;j+=i)          //j累加i,将有i这个素因子的所有数都进行运算
12                 phi[j]=phi[j]/i*(i-1);
13         }
14     }
15 }
16 int main(){
17     euler();
18     int n,m;
19     while(~scanf("%d%d",&n,&m)){
20         ll ans=0;
21         for(int i=n;i<=m;i++)
22             ans+=phi[i];
23         printf("%lld\n",ans);
24     }
25     return 0;
26 }

 

 

 

 

 

 

 

posted @ 2017-03-19 20:59  ZERO-  阅读(513)  评论(0编辑  收藏  举报