欧拉项目之求数值的和

来源:互联网 发布:淘宝店铺名字 大全 编辑:程序博客网 时间:2024/05/01 02:00

第一题:

描述:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000. 

(先思考,如果有兴趣先编程试试,然后才看下面的内容) 

 

分析: 

由于是第一题,所以非常简单,我稍稍分析一下

我们可以看看不超过20的数中3,5的倍数列表:3, 5, 6, 9, 10, 12, 15, 18, 20

很明显其可以撤成两类 3, 6, 9, 12, 15, 18 和 5, 10, 15, 20

他们分别是以3为首项3为等差的等差数列 以及 以5为首项5为等差的等差数列。或者理解成3的倍数的数列,以及5的倍数的数列

由于两个数列中存在3和5的公倍数,即为15,15*2,15*3......,结果将其减去即可。

以下是实现程序:

public class Test{

       public void main(String args[]){

                int sum=0;

                int n=1000-1;

                sum+=(n/3)*(999+3)+(n/5)*(995+5)-(n/15)*(n/15);

 

        }

 

}

 

 

当然等差数列的求和过程可以封装成一个函数,那就更清晰了。

 

public int s(int a1, int d, int n)
{
      int N  = max/d;
      int an = a1 + (N-1)*d;
      return (a1+an)*N/2;
}
 

第二题:

 

 

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

Find the sum of all the even-valued terms in the sequence which do not exceed four million.

 

一个Fibonacci数列,求4百万以下偶数的和。

 

 

public class Test {  
    public static void main(String args[]){  
       Test t=new Test();
       t.a();
       t.b();
    }  
  public void a(){
   int sum=2;  
      int a1,a2,a3=0;  
      a1 = 1;  
      a2 = 2;
      int i=0;
     
      while(a3<4000000){
          a3 = a1+a2;  
          a1 = a2;  
          a2 = a3;  
          i++;
          if(0==a3%2){  
              sum+=a3;
          }
        
      }  
      System.out.println(i);  
  }
  public void b(){
   int x=1,y=2;
   int z=0,q=0;
   int sum=2;
   z=x+y;  //第一个奇数
   q=y+z;  //第二个奇数
   int i2=0;
   while(z+q<4000000){
    sum+=(z+q);
    int temp=z+q;
    z=temp+q;
    q=temp+z;
    i2++;
   }
   System.out.println(i2);
  }

 

函数a()是我在网上看到一般的做法,函数b()是我自己的做法,算法复杂度为a()的1/3,而且是单纯的加法运算,这是计算机的强项。主要的想法是:1,2,3,5,8,13,21,34,。。。。。,   从2开始每个两个奇数就得到要加的偶数,所以我们只需要把这两个奇数(z,q)算出来就可以算出下一个要加的偶数(z+q),每次循环前进三个数,而a()每次循环只先前移了一个数。

 

看了看别人写的代码,还有不少人根据数列的规律优化了下.

规律大致是这样的

Fibonacci 数列 为(x=y=1)

x,y,x+y,x+2y,2x+3y,3x+5y...

红色的是偶数.

这样代码就可以写成下面

view plaincopy to clipboardprint?
def calcE():  
    x = y = 1 
    sum = 0 
    while (sum < 1000000):  
        sum += (x + y)  
        x, y = x + 2 * y, 2 * x + 3 * y  
    return sum 

 

原创粉丝点击