Skip to content

Instantly share code, notes, and snippets.

@stephanschubert
Created February 24, 2010 10:54
Show Gist options
  • Save stephanschubert/313326 to your computer and use it in GitHub Desktop.
Save stephanschubert/313326 to your computer and use it in GitHub Desktop.
Solution for Euler #25 in Ruby w/ memoization
# http://projecteuler.net/index.php?section=problems&id=25
# There are memoization libs, but i had it at my
# fingertips anyway ..
def memoize(name)
cache = {}
(class << self; self; end).send(:define_method, name) do |*args|
cache[args] = super(*args) unless cache.has_key?(args)
cache[args]
end
end
# Naive recursion
def fib(n)
return n if n < 2
fib(n-1) + fib(n-2)
end
# Enable memoization
memoize(:fib)
require "benchmark"
i = 1
limit = 10**999
puts Benchmark.measure { i += 1 while fib(i) < limit }.format("%r")
puts i
# => (0.030987)
# => 4782
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment