Excerpt from:  Marina Fedner
.
April 06, 2008

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.  

Topic Tags:  ,

Syndication OptionsRSS (Rich Site Summary) Feed Atom Feed OPML (Outline Processor Language) Feed MYST-ML (MyST Markup Language) Content Feed MS-Office Smart Tag Subscription