DEV Community

Valerie Woolard
Valerie Woolard

Posted on

Fibonacci Numbers & Project Euler Problem Two

Continuing on my series of going through the first 100 Project Euler problems, we're on to problem two. Here's problem one in case you missed it.

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

The Fibonacci sequence is a series of numbers in which the next number is the sum of the previous two.

The first time I solved this I think I probably checked if each number in the sequence was even, with a modulo similar to problem one, such as:

item % 2 == 0

But it occurred to me that the numbers follow a pattern, odd, odd, even so I could sum the even terms by adding together every third term.

I wrote a method to sum together all even Fibonacci numbers less than n. The solution is below or on GitHub

def sumOfEvenFibs(n):
  terms = [1, 1, 2]
  total = 0
  while terms[2] <= n:
    total += terms[2]
    t0 = terms[1] +  terms[2]
    t1 = terms[2] + t0
    terms = [t0, t1, t0 + t1]
  return total

print(sumOfEvenFibs(4000000))

Interested to see how others approached this one!

Discussion (0)