ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Lua Factorial Calculation

Lua

Goal -- WPM

Ready
Exercise Algorithm Area
1function calculateFactorial(n)
2-- Factorial is not defined for negative numbers.
3if n < 0 then
4return nil -- Indicate invalid input
5end
6
7-- The factorial of 0 is 1.
8if n == 0 then
9return 1
10end
11
12local result = 1
13-- Loop from 1 up to n (inclusive).
14for i = 1, n do
15result = result * i
16end
17
18return result
19end
20
21function factorialWithMemoization(n, memo)
22memo = memo or {}
23
24if memo[n] ~= nil then
25return memo[n]
26end
27
28if n < 0 then
29return nil
30end
31
32if n == 0 then
33return 1
34end
35
36local res = n * factorialWithMemoization(n - 1, memo)
37memo[n] = res
38return res
39end
Algorithm description viewbox

Lua Factorial Calculation

Algorithm description:

This Lua code calculates the factorial of a non-negative integer. It provides both an iterative approach and a recursive approach with memoization. Factorial is a fundamental mathematical concept used in combinatorics, probability, and series expansions.

Algorithm explanation:

The `calculateFactorial` function computes n! iteratively. It first handles edge cases: returning `nil` for negative inputs and `1` for `n=0`. For positive `n`, it initializes `result` to 1 and iterates from 1 to `n`, multiplying `result` by the current loop variable `i`. The time complexity is O(n) because of the single loop. The space complexity is O(1) as it only uses a few variables. The `factorialWithMemoization` function uses recursion with a memoization table (`memo`) to store previously computed factorial values. This avoids redundant calculations, making it more efficient for repeated calls with the same arguments. The time complexity with memoization becomes O(n) for the first call and O(1) for subsequent calls with already computed values. The space complexity is O(n) due to the memoization table and recursion depth.

Pseudocode:

function calculateFactorial(number):
  if number < 0:
    return invalid_input_indicator
  if number == 0:
    return 1
  
  initialize result = 1
  for i from 1 to number:
    result = result * i
  
  return result

function factorialWithMemoization(number, memo_table):
  if memo_table[number] exists:
    return memo_table[number]

  if number < 0:
    return invalid_input_indicator
  if number == 0:
    return 1

  recursive_result = number * factorialWithMemoization(number - 1, memo_table)
  store recursive_result in memo_table[number]
  return recursive_result