re: Project Euler #2 - Even Fibonacci numbers VIEW POST

FULL DISCUSSION
 

I went for what I thought was an interesting solution with Ruby this time. It uses a lazy enumerable over an infinite range and calculates the sum and the fibonacci numbers until the end condition is met.

def sum_even_fibonacci_numbers_up_to(max)
  range = 1..Float::INFINITY
  sum = 0
  last_two_fibs = [0,1]

  range.lazy.take_while do
    next_fib = last_two_fibs[0] + last_two_fibs[1] 
    sum += next_fib if next_fib % 2 == 0
    last_two_fibs = [last_two_fibs[1], next_fib]
    next_fib < max
  end.force

  sum
end

sum_even_fibonacci_numbers_up_to(4_000_000)
# => 4613732

This uses constant space, so does not compute an array of fibonacci numbers, just holds the latest two and the current sum. It runs in O(n) time and for 4,000,000 took less than 0.2s on my Macbook Pro.

code of conduct - report abuse