Search code examples
functionrecursionluafactorial

stack overflow error while implementing a Recursive Function(factorial)


I tried to implement a factorial function like this:

function factorial(n)
    if (n == 0) then
        return 1
    else
        return n * factorial(n - 1)
    end
end

io.write("number?")
n =io.read()
fac = factorial(n)
print("factorial of",n,"=",fac)

It works fine until I give 0 as input. It returns

lua: factorial.lua:5: stack overflow
stack traceback:
                factorial.lua:5: in function 'factorial'

What am I doing wrong?

Also, It gives normal output only till 16. when I give n=17, output is 3.55687428096e+014

How to get it right?


Solution

  • To get "0" to work, tell read to read a number: n = io.read("*n")

    To get the normal notation instead of scientific notation,use

    print("factorial of",n,"=",string.format("%0f",fac))