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
  • 119,891
  • 44
  • 235
  • 294
iamgr007
  • 966
  • 1
  • 8
  • 28
  • `n=17` answer is correct. It's just printed in scientific notation. – 001 Jul 12 '16 at 15:08
  • @JohnnyMopp yeah, what to do to get just the number? in normal representation. – iamgr007 Jul 12 '16 at 15:11
  • 1
    @Alaye http://stackoverflow.com/questions/1133639/how-can-i-print-a-huge-number-in-lua-without-using-scientific-notation – 001 Jul 12 '16 at 15:13
  • 3
    Also, to get "0" to work, tell `read` to read a number: `n = io.read("*n")` – 001 Jul 12 '16 at 15:16

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
  • 966
  • 1
  • 8
  • 28