如何在 Ruby 中编写递归阶乘函数?
How to write a recursive factorial function in Ruby?
我只是想得到一些关于如何在 Ruby 中编写递归阶乘函数的帮助。我有以下 lisp 代码,但我想在 Ruby 中做同样的事情。
(defun factorial (N)
(if (= N 1) 1
(* N (factorial (- N 1)))))
以下是如何在 ruby 中编写您的代码:
def factorial(n)
return 1 if n == 1
n * factorial(n - 1)
end
factorial(5)
#=> 120
factorial(7)
#=> 5040
编辑 Stefan 的评论:
要避免 n
值过大时出现 SystemStackError
错误,请使用 tail-recursive 方法。还必须启用 Ruby 的 tailcall
优化。
# before edit
factorial(100_000).to_s.size
#=> stack level too deep (SystemStackError)
避免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
我只是想得到一些关于如何在 Ruby 中编写递归阶乘函数的帮助。我有以下 lisp 代码,但我想在 Ruby 中做同样的事情。
(defun factorial (N)
(if (= N 1) 1
(* N (factorial (- N 1)))))
以下是如何在 ruby 中编写您的代码:
def factorial(n)
return 1 if n == 1
n * factorial(n - 1)
end
factorial(5)
#=> 120
factorial(7)
#=> 5040
编辑 Stefan 的评论:
要避免 n
值过大时出现 SystemStackError
错误,请使用 tail-recursive 方法。还必须启用 Ruby 的 tailcall
优化。
# before edit
factorial(100_000).to_s.size
#=> stack level too deep (SystemStackError)
避免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