简体   繁体   中英

Finding the sum of even valued terms in fibonacci sequence using for loop

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.

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)

How can i solve this using for loop?

The Fibonacci sequence reaches 4000000 from the 34th element

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM