Project Euler #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, …

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

We are given our bounds in the problem,  1..4000000 , and we are to find and sum every even fibonacci number inside the given bounds.

To start off, we should define a function to generate a list of fibonacci numbers.  I opted for a recursive function, but this could easily be achieved using simple loops as well.

def fib(nums, maxNum):
    if not (nums[-1] >= maxNum):
        nums.append(nums[-1] + nums[-2])
        fib(nums, maxNum)
    return nums

With that function defined, the rest of the problem is simply iterating through the array of fibonacci numbers, testing if they are even, and adding them to a sum value.

Leave a Reply