LoginSignup
3
5

More than 5 years have passed since last update.

ruby 階乗計算 再帰関数

Last updated at Posted at 2014-12-27

require 'benchmark'

# 階乗計算(再帰)
def fact(n)
  return 1 if n == 0
  n * fact(n - 1)
end

Benchmark.bm do |x|
   x.report { p fact(100) }
end

# 階乗計算(末尾再帰)
def facti(n, a = 1)
  return a if n == 0
  facti(n - 1, n * a)
end

Benchmark.bm do |x|
   x.report { p facti(100) }
end

3
5
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5