假设我想用以下递归方式在 Julia 中编写阶乘函数:
FACTORIAL(n) = n==1 ? 1 : n*BigInt(FACTORIAL(n-1))
这样做,在尝试计算
FACTORIAL(1e6)
时会显示以下错误:
julia> FACTORIAL(1e6)
ERROR: StackOverflowError:
Stacktrace:
[1] FACTORIAL(n::Float64) (repeats 65428 times)
@ Main ./REPL[36]:1
[2] top-level scope
@ REPL[38]:1
但是,人们可能很容易看出
factorial(BigInt(1e6))
不会引发溢出错误。
请注意,我的问题是一般性的,而不是关于阶乘函数本身。我在其他一些递归编写的函数中看到过这种行为。
function FACTORIAL(n)
res = 1
for i in 1:n
res *= i
end
return res
end