Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 820
iamgr007 Avatar asked Mar 15 '26 05:03

iamgr007


1 Answers

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))
like image 144
iamgr007 Avatar answered Mar 18 '26 11:03

iamgr007



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!