3

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?

Yu Hao
  • 115,525
  • 42
  • 225
  • 281
iamgr007
  • 990
  • 1
  • 8
  • 27

1 Answers1

2

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))
iamgr007
  • 990
  • 1
  • 8
  • 27