Skip to content

Instantly share code, notes, and snippets.

@bil-bas
Created October 22, 2012 22:09
Show Gist options
  • Save bil-bas/3934913 to your computer and use it in GitHub Desktop.
Save bil-bas/3934913 to your computer and use it in GitHub Desktop.
Memoising Integer#factorial in Ruby
# Memoising factorial method.
class Integer
class << self
def factorial_results(number)
raise "number has to be greater than 0" if number < 0
@factorial_results ||= begin
results = Hash.new do |h, k|
h[k] = k * @factorial_results[k - 1]
end
results[0] = 1 # Need a base-line.
results
end
@factorial_results[number]
end
end
def factorial
Integer.factorial_results self
end
end
p 0.factorial #=> 1
p 1.factorial #=> 1
p 5.factorial #=> 120
p 35.factorial #=> 10333147966386144929666651337523200000000
# Perfectly acceptable way to do it!
p 35.downto(1).reduce {|m, i| m * i } #=> 10333147966386144929666651337523200000000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment