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…
好像存在这种关系:
如果我们能证明:
便也就证明了上式.
证明如下:
F(n)
=F(n−1)+F(n−2)
=F(n−2)+F(n−3)+F(n−2)
=2F(n−2)+F(n−3)
=2(F(n−3)+F(n−4))+F(n−3)
=3F(n−3)+2F(n−4)
=3F(n−3)+F(n−4)+F(n−5)+F(n−6)
=4F(n−3)+F(n−6)
证毕.
这种形式可以避免奇偶判断.