Sum of even fibonacci numbers below 4 million - Python

fibonacci, if-statement, math, python

Solution

The problem is in the line `counter+= (counter -1)`. You add it to itself (minus 1) while you should be doing this:

a, b = 1, 1
total = 0
while a <= 4000000:
    if a % 2 == 0:
        total += a
    a, b = b, a+b  # the real formula for Fibonacci sequence
print total

Problem

I'm attempting the second Project Euler question in python and want to understand why my code doesn't work. This code finds the sum of even Fibonacci numbers below 4 million ``` counter = 2 total = 0 while counter <= 4000000: if counter % 2 == 0: total+= counter counter+= (counter -1) print total ``` This code will output: 2 If I print the counter it outputs: 4194305 I'm assuming it's an issue with the if statement being executed as the while loop is functioning correctly and the counter is also incrementing correctly.

Original source