Problem 2
来源:互联网 发布:ping监控软件 编辑:程序博客网 时间:2024/05/11 23:02
Each new term in theFibonacci sequence is generated by adding the previous two terms. By startingwith 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13,21, 34, 55, 89, ...
Find the sum of allthe even-valued terms in the sequence which do not exceed four million.
Fibonacci序列中的每一个新元素都是前两个元素之和。由1和2开始,前十个元素为:
1, 2, 3, 5, 8, 13,21, 34, 55, 89, ...
找到这个序列中所有不超过4百万的偶数元素之和。
最简单的方法:
对一个Fibonacci序列循环,判断当前值是否是偶数,如果是偶数,加入到总和里,一直加到当前元素值大于4百万。
- def fibsum1(n):
- sum = 0
- a, b = 1, 2
- while b < n:
- if (b%2 == 0):
- sum += b
- a, b = b, a+b
- return sum
还有稍微复杂点的方法:
可以观察到,在该序列中每隔2个数为偶数,所以只要循环的时候加两次就可以了,这样能够避免取余的操作了。
- def fibsum2(n):
- sum = 0
- a = 1
- b = 1
- c = a + b
- while c < n:
- sum = sum + c
- a = b + c
- b = c + a
- c = a + b
- return sum
在这个问题的相应回帖中,贴出了一个python的解答。
每隔两个奇数有一个偶数,则可以看出Fibonacci序列为:
x, y, x + y, x + 2y, 2x + 3y, 3x + 5y
前两个奇数为x,y时,后两个奇数为x+2y, 2x+3y, 每个偶数为前两个奇数的和。所以程序可为:
- def fibsum3(n):
- x = y = 1
- sum = 0
- while (y < n):
- sum += (x + y)
- x, y = x + 2 * y, 2 * x + 3 * y
- return sum
进行一下测试,
- if __name__ == '__main__':
- print fibsum1(4000000)
- print fibsum2(4000000)
- print fibsum3(4000000)
结果是:4613732
- Problem 2
- Problem 2
- problem 2
- Problem 2
- Problem 2
- Problem 2 of Fibonacci
- Project Euler - Problem 2
- Project Euler problem 2
- 2Sum Problem
- 2:A-B Problem
- 2 Egg Problem
- projecteuler---->problem:2
- Problem 2 ---- euler
- 2 sum problem
- USACO 1.1 Problem 2
- USACO 1.2 Problem 2
- Project Euler Problem 2
- a+b problem 2
- 六级听力及阅读理解超高频词汇精华
- 删除那些无法被删除的文件
- GTK入门
- 编译器专业术语
- 局部动态可重配置体会
- Problem 2
- EAPR简介
- SQL语法
- open和fopen的区别
- 前方的路需要自己去走,自己去适应和体验!
- 如何把一个array复制到arrayList里
- 决定明天开始使用:开源记账软件GnuCash 2.2.7便携版
- 垂直计划
- 热烈祝贺小强和小小叶乔迁之喜!