Lua Program to Find Factorial of a Number

Write a program to find factorial of a number in Lua.

For example,

Input
5
Output
120

Lua Program to Find Factorial of a Number Using Loop

function factorial(n)
	fact = 1
	for i = 1, n, 1
	do
		fact = fact * i
	end
	return fact
end

io.write("Enter a Number: ")
n = io.read("*n")
io.write("Factorial of ", n, " = ", factorial(n))

Lua Program to Find Factorial of a Number Using Recursion

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

io.write("Enter a Number: ")
n = io.read("*n")
io.write("Factorial of ", n, " = ", factorial(n))

Note

Using a loop is much more efficient than using recursion. Recursion uses an internal stack to store the information of the recursive calls. This leads to more compution and additional memory usage.

Leave a Comment