[欧拉计划]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数列:
不难证明每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)
证毕.
这种形式可以避免奇偶判断.
0 0
- [欧拉计划]Problem 2.Even Fibonacci numbers
- 【欧拉计划2】Even Fibonacci numbers
- 欧拉计划(2)Even Fibonacci numbers
- 欧拉计划---0002 Even Fibonacci numbers(四百万以内斐波纳契偶数和)
- Problem 2:Even Fibonacci numbers
- Problem 2 Even Fibonacci numbers
- 欧拉项目第二题 Even Fibonacci numbers
- 【Project Euler】【Problem 2】Even Fibonacci numbers
- (Problem 2)Even Fibonacci numbers
- Project Euler Problem 2: Even Fibonacci numbers
- Problem 2 Even Fibonacci numbers (fibonacci 数学规律)
- Even Fibonacci numbers
- [projecteuler]Even Fibonacci numbers
- Even Fibonacci numbers
- PE2-Even Fibonacci numbers
- PE 2 Even Fibonacci numbers
- 2 Even Fibonacci numbers - Project Euler
- Project Euler 002 Even Fibonacci numbers
- uva 10794
- OC循环渐进:开闭原则和里氏替换原则
- linux 内核调试(一)
- 转自“奇谈怪论” 网易博客 事务处理总结:JDBC事务|JTA事务|容器事务
- Study-android 各种dialog的学习总结
- [欧拉计划]Problem 2.Even Fibonacci numbers
- 2015 Multi-University Training Contest 6_1008_Hiking(贪心)
- Web Api简单用法
- 理解Java ClassLoader机制(转载)
- Python实用入门
- 开源日志系统比较:scribe、chukwa、kafka、flume
- 手机查看测试中的网页
- JS输入用户名自动显示邮箱后缀列表的方法
- WebApplicationContext里面的一些特殊的bean