Skip to content

Instantly share code, notes, and snippets.

@rantler
Created June 1, 2017 21:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rantler/1d76ca2193c9a3e5f7c14675f5295d63 to your computer and use it in GitHub Desktop.
Save rantler/1d76ca2193c9a3e5f7c14675f5295d63 to your computer and use it in GitHub Desktop.
Example of fast fibonacci algorithm in Ruby
# Cribbed from https://stackoverflow.com/questions/24438655/ruby-fibonacci-algorithm
def fib_memo(n, memo)
memo[n] ||= fib_memo(n-1, memo) + fib_memo(n-2, memo)
end
def fib(n)
raise "fib not defined for negative numbers" if n < 0
fib_memo(n, [0, 1])
end
def timer
n = Time.now
yield
puts "#{(Time.now - n) * 1_000}ms"
end
timer { fib(42) } # 0.013ms on my laptop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment