05.28.08

Project Euler: Problem 2

Posted in python tagged , , at 3:15 pm by redochre

Problem 2:

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, …

Find the sum of all the even-valued terms in the sequence which do not exceed four million.

A Solution:

target = 4000000
a = 0
b = 1
c = 1
sum = 0

while c <= target:
    if c % 2 == 0:
        sum += c
    a = b
    b = c
    c = a+b

print sum

The problem talks about starting with 1 and 2, but if we start as shown above with 0 and 1, the first 2 will get caught in the while loop.

Update (2 days later):
I’ve gone back and prettied up a few of my solutions. In the solution that follows the number of variables necessary to keep goes down to two from three, because the right side of an equation (including multiple assignments) is evaluated before any of the assignments get made. Sneaky.

target = 4000000
a, b, sum = 0, 1, 0

while b <= target:
    if b % 2 == 0:  sum += b
    a, b = b, a+b

print sum