Lazy Evaluation

Marina's coding (mis)adventures
Project Euler: Problem 2

The problem: 

Find the sum of all the even-valued terms in the [Fibonacci] sequence which do not exceed four million.

 

Here's my fibonacci function:

def fib(limit =nil)
  f1 = 0
  f2 = 1
  while (not limit or f2 <= limit)
      yield f2
      f1,f2 = f2, f1+f2
  end
end

And here's how I use it to get the answer:

evens=[]
fib { |x| if x%2==0 : evens.push(x) end ; if x>4000000: break end}
puts evens.inject {|sum, n| sum+n}

 

I learned about the awesomeness of 'yield' by doing this problem, so it was totally worth it.  yield let me calculate as many fibonacci terms as I needed, but not more, and without having to calculate any term more than once.  

Published Sun, Apr 6 2008 7:55 PM by mfedner

Filed under: ,

Comments

# re: Project Euler: Problem 2@ Monday, October 20, 2008 1:23 PM

Or, more simply: fib(4000001) - 1

Calculating that is pretty simple. :)

In general, \sum_{i=0}^n F_{2i} = F_{2n+1} - 1, or, in English, the sum of the first n even terms of the Fibonacci sequence is the (2n+1)th Fibonacci number minus one.

Here n = 2,000,000

Jesse Farmer

Leave a Comment

(required) 
(required) 
(optional)
(required)