Project-Euler Ruby

What is Project Euler

Project Euler is a website with a collection of programming and mathematical problems. Each challenge varies in difficulty and there are over 600 challenges. I highly recommend anyone interested in puzzles and programming to create an account and start solving. About Project Euler

** Stop here if you have not yet tried and solved Problem 2. **

**

**

**

**

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.

class Problem2
  require 'benchmark'

  def question
    "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."
  end


  def fibonacci_even_sum(limit = 4000000)
    sum = 2
    runner = 2
    one_back = 1
    two_back = 0

    while(runner <= limit)
      sum += runner if runner.even?

      two_back = one_back
      one_back = runner
      runner = two_back + one_back
    end

    sum
  end

  def solve
    fibonacci_even_sum
  end

  def benchmark
    Benchmark.measure { solve }
  end

  def correct?
    solve === answer
  end

  private

  def answer
    4613732
  end
end

 

Did you like this article? Check out these too.


 

Found this useful? Know how it can be improved? Get in touch and share your thoughts at blog@hocnest.com