如何在Ruby中编写递归阶乘函数?

Wah*_*h.P 4 ruby lisp recursion factorial

我只需要一些有关如何在Ruby中编写递归阶乘函数的帮助。我有以下Lisp代码,但我想在Ruby中做同样的事情。

(defun factorial (N)
    (if (= N 1) 1
        (* N (factorial (- N 1)))))
Run Code Online (Sandbox Code Playgroud)

dem*_*mir 5

这是用ruby编写代码的方法:

def factorial(n)
  return 1 if n == 1
  n * factorial(n - 1)
end

factorial(5)
#=> 120
factorial(7)
#=> 5040
Run Code Online (Sandbox Code Playgroud)

编辑Stefan的评论:

为避免SystemStackError使用的大值错误n,请使用尾递归方法。同样,tailcall必须启用Ruby的优化。

# before edit
factorial(100_000).to_s.size
#=> stack level too deep (SystemStackError)
Run Code Online (Sandbox Code Playgroud)

避免 SystemStackError

RubyVM::InstructionSequence.compile_option = {
  tailcall_optimization: true,
  trace_instruction: false
}

RubyVM::InstructionSequence.new(<<-CODE).eval
  def factorial(n, acc = 1)
    return acc if n == 1
    factorial(n - 1, n * acc)
  end
CODE

puts factorial(100_000).to_s.size
#=> 456574
Run Code Online (Sandbox Code Playgroud)

资源1 资源2

  • 或者,如果您在哪里更确切地翻译lisp代码:`n == 1?1:n * factorial(n-1)`,但我自己更喜欢后卫版本。 (2认同)