Let's say I want to write the factorial function in Julia in the following recursive way:
FACTORIAL(n) = n==1 ? 1 : n*BigInt(FACTORIAL(n-1))
Doing so, it shows the following error when trying to compute 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
However, one may easily see that factorial(BigInt(1e6)) does not throw an overflow error.
- I wonder what is wrong with the recursive code that results in such an error?
- Is there a way to write such a function recursively which avoids such an error?
Note that my question is general and not about the factorial function by itself. I have seen such a behavior with a few other functions written recursively.