Project Euler: Problem #2 – Even Fibonacci Numbers

Today I started a Project Euler account and began working through a few of the problems. They are really fun problems! I highly recommend starting an account if you haven’t already, it’s free anyways…


Description

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.


The solution is really basic, and Python makes the solution elegant. Simply perform the basic Fibonacci Sequence, namely

F_{n} = F_{n-1} + F_{n-2}

where F_{0} = 0 and F_{1}=1.

To ensure that only the even numbers in the sequence are added to the sum, I simply add an if statement that only evaluates to true when the left hand operand can be divided by two evenly. Here’s my solution, tell me what you think.

def sum_even_fib(n):
 sum = 0
 a, b = 0, 1
 while b < n:
  a, b = b, a + b
  if b % 2 == 0:
   sum = sum + b
 return sum

print(sum_even_fib(4000000))

Leave a Reply

Your email address will not be published. Required fields are marked *