Skip to content

Instantly share code, notes, and snippets.

@wenzowski
Created January 26, 2013 21:48
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 wenzowski/4644838 to your computer and use it in GitHub Desktop.
Save wenzowski/4644838 to your computer and use it in GitHub Desktop.
factorial lookup table
##
# Factorial[positive_integer] computes and memoizes the
# factorial of a given positive integer.
module Factorial
class << self
def [](n)
@factorial_table ||= Hash.new { |hash, key|
hash[key] = (1..key).reduce(:*) || 1
}
@factorial_table[n]
end
end
end
require 'benchmark'
a = 13
b = 37
r = 100000
Benchmark.bm do |x|
x.report do
r.times do
(a..b).each {|i| (1..i).reduce(:*) }
end
end
x.report do
r.times do
(a..b).each {|i| Factorial[i] }
end
end
end
# My Results
# ==========
#
# user system total real
# 9.180000 0.020000 9.200000 ( 10.834001)
# 0.710000 0.010000 0.720000 ( 0.706927)
#
# You should probably run the benchmark yourself to get relevant data.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment