使用for循环在斐波那契数列中查找偶值项的总和

时间:2019-01-10 14:52:38

标签: python

斐波那契数列中的每个新术语都是通过将前两个术语相加而生成的。从1和2开始,前10个术语将是: 1,2,3,5,8,13,21,34,55,89,... 通过考虑斐波那契数列中值不超过四百万的项,找到偶值项的总和。

prev, cur = 0, 1
total = 0
while True:
    prev, cur = cur, prev + cur
    if cur >= 4000000:
        break
    if cur % 2 == 0:
        total += cur
print(total)

如何使用for循环解决此问题?

2 个答案:

答案 0 :(得分:0)

斐波那契数列从第34个元素开始达到4000000

prev, cur = 0, 1
total = 0
for i in range(34):
    prev, cur = cur, prev + cur
    if cur % 2 == 0:
        total += cur
print(total)

答案 1 :(得分:0)

first = 0
second = 1
for i in range(1,4000000):
    next=(first+second)
    print(next)
    first=second
    second=next