Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 28 lines (23 sloc) 0.709 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
# 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.
# Solution: 4613732

def isEven?(n)
  n % 2 == 0
end

def fib_term_sum(limit, test)
  term = 0
  n = 3
  vals = [0, 1]

  begin
    (n-1).times do
      vals.push(vals[-1] + vals[-2])
    end
    term = vals.last
    n += 1
  end until term > limit
  
  vals.first(vals.length-1).reduce(0) do |sum, x|
    sum += test.call(x) ? x : 0
  end
end

puts fib_term_sum(400000, method(:isEven?))
Something went wrong with that request. Please try again.