Skip to content

Instantly share code, notes, and snippets.

@varyform
Created April 17, 2014 21:56
Show Gist options
  • Save varyform/11013785 to your computer and use it in GitHub Desktop.
Save varyform/11013785 to your computer and use it in GitHub Desktop.
fib with memo
# Fibonacci numbers WITH memoization.
# Initialize the memoization array.
@scratchpad = []
# Calculate the nth Fibonacci number, f(n).
def fibo(n)
if n <= 1
n
else
@scratchpad[n] ||= fibo(n-1) + fibo(n-2)
end
end
# Display the Fibonacci sequence.
1.upto 100 do |number|
puts "fibo(#{number}) = #{fibo(number)}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment