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

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数列:

F1123581321345589144
abcabcabcabc
****

不难证明每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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值