0

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
  • 3
    a stack a million frames deep? or did you think Julia would optimize this recursion? Commented Feb 23, 2024 at 22:46

1 Answer 1

0

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.