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

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.

# 方法一:
i = 0
list1 = [1, 2]
def add():
    if list1[len(list1)-1] < 4000000:
        i = list1[len(list1)-1] + list1[len(list1)-2]
        list1.append(i)
        add()
    elif list1[len(list1)-1] > 4000000:
        list1.pop(-1)
add()
for each in list1:
    if each % 2 == 0:
        i = i + each
print(i)
# 方法二:
limint = 4000000
sum = 0
a = 1
b = 1
c = a + b
while b < limint:
    sum = sum + c
    a = b + c
    b = c + a
    c = a + b
print(sum)

 

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