400 万以下的斐波那契数列 [英] Fibonacci under 4 millions
本文介绍了400 万以下的斐波那契数列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复:
查找斐波那契数列的 Python 程序.更多 Pythonic 方式.
嘿,我正在尝试编写一个脚本,将斐波那契数列"中的所有偶数项汇总到 400 万以下.
Hey, i was trying to write a script which sums all the even terms in "Fibonacci Sequence" under 4 millions.
Fibonacci1 = 1
Fibonacci2 = 2
a = 2
i = 4
for i in range(1,4000000):
Fibonacci1 = Fibonacci1 + Fibonacci2
if Fibonacci1 % 2 == 0:
a = a + Fibonacci1
Fibonacci2 = Fibonacci1 + Fibonacci2
if Fibonacci2 % 2 == 0:
a = a + Fibonacci2
print a
raw_input()
应该不到一分钟的时间,但花了整整一夜的时间都没有解决!
it should takes less than a minute, but it took all night and it wasn't solved !
抱歉各位,我误解了这个问题.我虽然这意味着我必须将所有偶数项相加到 400 万!但解决方案是将所有偶数项相加,直到 400 万.
Sorry guys, i misunderstood the problem. I though it means that i have to sum all the even terms UP TO 4 million ! But the solution was to sum all the even terms UNTIL 4 million.
工作代码(不到一秒完成):
Working code (finished in less than one second):
Fibonacci1 = 1
Fibonacci2 = 2
a = 2
while a < 4000000:
Fibonacci1 = Fibonacci1 + Fibonacci2
if Fibonacci1 % 2 == 0:
a = a + Fibonacci1
Fibonacci2 = Fibonacci1 + Fibonacci2
if Fibonacci2 % 2 == 0:
a = a + Fibonacci2
print a
raw_input()
推荐答案
循环条件不对,应该是这样的:
The loop condition is wrong, it should be something like this:
while True:
Fibonacci1 = Fibonacci1 + Fibonacci2
if Fibonacci1 % 2 == 0:
if a + Fibonacci1 > 4000000:
break
a = a + Fibonacci1
Fibonacci2 = Fibonacci1 + Fibonacci2
if Fibonacci2 % 2 == 0:
if a + Fibonacci2 > 4000000:
break
a = a + Fibonacci2
这篇关于400 万以下的斐波那契数列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文