Created
January 26, 2013 21:48
-
-
Save wenzowski/4644838 to your computer and use it in GitHub Desktop.
factorial lookup table
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
## | |
# 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