[欧拉计划]Problem 2.Even Fibonacci numbers

来源:互联网 发布:蓝光主板端口说明 编辑:程序博客网 时间:2024/05/20 04:32

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, …

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

首先最容易想到的方法:

int limit = 4000000, sum = 0, a = 1, b = 1;while(b < limit){  if(b % 2 == 0)    sum += b;  int h = a + b;  a = b;  b = h;}cout << sum << endl;

这样做一定是把4000000以内的fibnacci数列遍历了一遍,那么有没有效率更高的算法呢?

我们先写出一段fibnacci数列:

F 1 1 2 3 5 8 13 21 34 55 89 144 a b c a b c a b c a b c * * * *

不难证明每3项都是偶数,因此程序也可以写成这样:

int limit = 4000000, sum = 0, a = 1, b = 1, c = a + b;while(c < limit){  sum += c;  a = b + c;  b = c + a;  c = a + b;}cout << sum << endl;

但是效率并没有提高,依然是将数列遍历了一遍.

我们把偶数项单独写出来,会发现一个优美的结构

2,8,34,144…

好像存在这种关系:

E(n)=4E(n1)+E(n2)

如果我们能证明:
F(n)=4F(n3)+F(n6)

便也就证明了上式.

证明如下:

F(n)
=F(n1)+F(n2)
=F(n2)+F(n3)+F(n2)
=2F(n2)+F(n3)
=2(F(n3)+F(n4))+F(n3)
=3F(n3)+2F(n4)
=3F(n3)+F(n4)+F(n5)+F(n6)
=4F(n3)+F(n6)

证毕.
这种形式可以避免奇偶判断.

0 0
原创粉丝点击