Created
February 5, 2010 18:39
-
-
Save stephanschubert/296073 to your computer and use it in GitHub Desktop.
Recursive fibonacci with memoization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
def fib(n) | |
return n if n < 2 | |
fib(n-1) + fib(n-2) | |
end | |
memoize(:fib) | |
fib(100) # => 354224848179261915075 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment