Project Euler Problem 2 – Even Fibonacci Numbers

02.04.2015

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.

To solve this problem, I first started by writing a simple test case to test that this would work with numbers under 10. We know that our answer would be 10 since 2 and 8 are the only even numbers in the Fibonacci sequence. The test instantiates a Problem2 solver object with 10 as the parameter. We solve and should expect 10 as the answer.

class Problem2Test < Minitest::Unit::TestCase
  def test_even_fibonacci_numbers
    solver = Problem2.new :under => 10
    answer = solver.solve
    assert_equal 10, answer
  end
end

The test should be failing since we haven’t implemented the class yet. The next step is to implement the class.

class Problem2
  def initialize options
    @under = options[:under]
  end

  def solve
    previous = 0
    current = 1
    sum = 0
    loop do
      temp = current
      current += previous
      previous = temp
      break if current >= @under
      sum += current if current % 2 == 0
    end
    sum
  end
end

In the solve method, we start by declaring 3 variables, previous, current, and sum. In the loop, we store the current as temp, which we will use to set the previous later on. We add the previous to the current and then set the previous to the temp. We stop the loop if the current is equal to or greater than the under instance variable we initialized earlier. We add current to the sum if it is even. We return the sum.

Then we solve for the answer:

puts Problem2.new(:under => 4000000).solve

https://github.com/travisluong/projecteuler