Skip to content

Instantly share code, notes, and snippets.

@ryanswood
Last active August 29, 2015 14:00
Show Gist options
  • Select an option

  • Save ryanswood/11269784 to your computer and use it in GitHub Desktop.

Select an option

Save ryanswood/11269784 to your computer and use it in GitHub Desktop.
Factorial Recursion
require 'benchmark'
def factorial(n)
if n <= 1
n
else
n * factorial(n-1)
end
end
# 0.041621
def tail_factorial(n, acc = 1)
if n <= 1
acc
else
tail_factorial(n-1, acc * n)
end
end
Benchmark.bm do |x|
x.report {factorial(8500)}
x.report {tail_factorial(8500)}
end
# Results:
# user system total real
# 0.050000 0.010000 0.060000 ( 0.049929)
# 0.050000 0.010000 0.060000 ( 0.071022)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment