简体   繁体   中英

Program never completes when loop is set to 4000000

fib1 = 1
fib2 = 2

i = 0
sum = 0

while i < 3999998:

    fibn = fib1 + fib2

    fib1 = fib2
    fib2 = fibn

    i += 1

    if fibn % 2 == 0:
        sum = sum + fibn

print(sum + 2)

The challenge is to add even Fibonacci numbers under 4000000. It works for small limits say 10 numbers. But goes on forever when set for 4000000. Code is in Python

Yes, there are inefficiencies in your code, but the biggest one is that you're mistaken about what you're computing.

At each iteration i increases by one, and you are checking at each step whether i < 3999998 . You are effectively finding the first 4 million fibonacci numbers .

You should change your loop condition to while fib2 < 3999998 .

A couple of other minor optimisations. Leverage python's swapping syntax x, y = y, x and its sum function. Computing the sum once over a list is slightly faster then summing them up successively over a loop.

a, b = 1, 2
fib = []
while b < 3999998:
   a, b = b, a + b
   if b % 2 == 0:
      fib.append(b)

sum(fib) + 2

This runs in 100000 loops, best of 3: 7.51 µs per loop , a whopping 3 microseconds faster than your current code (once you fix it, that is).

You are computing the first 4 million fibonacci numbers. It's going to take a while. It took me almost 5 minutes to compute the result, which was about 817 KB of digits, after I replaced fibn % 2 == 0 with fibn & 1 == 0 - an optimization that makes a big difference on such large numbers.

In other words, your code will eventually finish - it will just take a long time.

Update: your version finished after 42 minutes.

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