xRay
xRay

Reputation: 19

Python _ Project Euler Question 2 - Why my answer code is wrong?

Q: By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

My Code:

x = 1
y = 2
ans = 0
evens = []
while x <= 4000000:
    ans = x + y
    x = y
    y = ans
    if ans % 2 == 0:
        evens.append(ans)
print(sum(evens))

My result is 4613730 while it should be 4613732. What am I don't understand here?

Upvotes: 0

Views: 98

Answers (2)

Park
Park

Reputation: 2484

You can use print(evens) inside loop to see what you missed. Now, first 2 is not printed.

First even, 2, is not inserted to the evens, so one of ways to correct the code is inserting 2 into evens right before starting a loop. There might be many ways to solve this issue.

x = 1
y = 2
ans = 0
evens = [2]
while x <= 4000000:
    ans = x + y
    x = y
    y = ans
    if ans % 2 == 0:
        evens.append(ans)
    print(evens) # to debug what are in in a 'evens' list
print(sum(evens)) 
# 4613730

Upvotes: 1

JamesRoberts
JamesRoberts

Reputation: 66

You are skipping over 2.

ans is first checked with the value of 3.

ans = x + y is 3 since you start with x = 1 and y = 2

Upvotes: 1

Related Questions