Skip to content. | Skip to navigation

Personal tools
You are here: Home Programming Python Project Euler 002 - find the sum of the fibonacci sequence

002 - find the sum of the fibonacci sequence

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

Problem 2 asks:

The Fibonacci sequence is generated by adding the previous two terms. (Starting with 1 and 2, it goes 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 one million.

This is trickier than Problem 1. Iterating over each number less than 1,000,000 would be foolishly inefficient. So it seems the best way to approach this would be to generate the Fibonacci numbers directly. A generating function can be written like this:

def gen_fibo():
   two_back = 0
   one_back = 1
   while 1:
      curr_answer = two_back + one_back
      two_back = one_back
      one_back = curr_answer
      yield curr_answer

We can grab successive item in the sequence from this:

for x in gen_fibo():
   print x
   if x > 100:
      break

giving:

1
2
3
5
8
13
21
34
55
89
144

Thus we can grab the numbers from the sequence, test them for "even-ness" and sum those, until the item surpasses a million:

>>> sum = 0
>>> for x in gen_fibo():
....:     if (1000000 < x):
....:         break
....:     elif (x % 2) == 0:
....:         sum += x
....:

>>> sum
1089154
Document Actions
Visitors
Locations of visitors to this page
Ads
 
Sections