Saw's Blog Saw's Blog

Euler Project - Problem 2

Attempt at problem 2. Not my first rodeo, but enjoyable regardless.

Even Fibonacci numbers

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

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

https://projecteuler.net/problem=2

This problem here is pretty straight forward. First we get all the Fibonacci numbers under 4 million, remove the even valued terms, then sum them up.
import pprint
pp = pprint.PrettyPrinter(indent=4, compact=True)

# The first thing that comes to mind to solve this is to google the fibonacci algorithm
# https://stackoverflow.com/questions/18172257/efficient-calculation-of-fibonacci-series
# will give us the function needed to get started

def fib_to(n):
  fibs = [0, 1]
  for i in range(2, n+1):
      fibs.append(fibs[-1] + fibs[-2])    
  return fibs

Here I generated a list of 50 Fibbonaci numbers to see if any of them exceeds 4 million. Once we get a list of Fibbonaci numbers that covers sufficient range (in this case, numbers up till 4 million), then we can just start cleaning it up and work our magic.
# Generate list of fibbonaci numbers
fib_list_to_50 = fib_to(50)
pp.pprint(fib_list_to_50)
OUTPUT:
[   0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597,
  2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811,
  514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352,
  24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437,
  701408733, 1134903170, 1836311903, 2971215073, 4807526976, 7778742049,
  12586269025]

Halfway through the list, we can see some numbers already started exceeding 4 million, like 5702887. Now we just have to clean up the list.
# Remove the first two numbers
fib_list_to_50_clean = fib_list_to_50[2:]
fib_list_even = list(filter(lambda x : x%2 == 0, fib_list_to_50_clean))
fib_list_less_than_4mil = list(filter(lambda x : x < 4000000, fib_list_even))
pp.pprint(fib_list_less_than_4mil)
OUTPUT:
[2, 8, 34, 144, 610, 2584, 10946, 46368, 196418, 832040, 3524578]

sum(fib_list_less_than_4mil)
OUTPUT:
4613732
Which is the sum we are looking for.
comments powered by Disqus