Created
February 24, 2010 10:54
-
-
Save stephanschubert/313326 to your computer and use it in GitHub Desktop.
Solution for Euler #25 in Ruby w/ 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
# 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