Why does Julia BigInt iterative functions overflow?

48 Views Asked by At

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.

  1. I wonder what is wrong with the recursive code that results in such an error?
  2. 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.

1

There are 1 best solutions below

0
Oscar Smith On

The stack overflow is easy to fix by changing recursion to a loop.

function FACTORIAL(n)
    res = 1
    for i in 1:n
        res *= i
    end
    return res
end