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

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

Octave Recursive Factorial Calculation

Octave

Goal -- WPM

Ready
Exercise Algorithm Area
1function result = recursiveFactorial(n)
2% Calculates the factorial of a non-negative integer using recursion.
3% Factorial of n (n!) is the product of all positive integers less than or equal to n.
4% For example, 5! = 5 * 4 * 3 * 2 * 1 = 120.
5% By definition, 0! = 1.
6
7% --- Input Validation and Edge Cases ---
8% Factorial is not defined for negative numbers.
9if n < 0
10error('Factorial is not defined for negative numbers.');
11end
12
13% --- Base Case ---
14% The factorial of 0 is 1.
15if n == 0
16result = 1;
17% --- Recursive Step ---
18% For any positive integer n, n! = n * (n-1)!
19else
20result = n * recursiveFactorial(n - 1);
21end
22end
Algorithm description viewbox

Octave Recursive Factorial Calculation

Algorithm description:

This Octave function calculates the factorial of a non-negative integer using a recursive approach. The factorial of a number `n` is the product of all positive integers up to `n`. This recursive implementation is a classic example of how recursion can elegantly solve problems with self-similar subproblems.

Algorithm explanation:

The `recursiveFactorial` function computes the factorial of a non-negative integer `n`. It first checks for invalid input: if `n` is negative, it throws an error because the factorial is not defined for negative numbers. The function then defines its base case: if `n` is 0, it returns 1, as 0! is defined as 1. For any positive integer `n`, the function enters the recursive step: it returns `n` multiplied by the result of calling itself with `n-1`. This process continues until the base case (`n=0`) is reached, at which point the results are multiplied back up the call stack. The time complexity is O(n) because the function makes `n` recursive calls. The space complexity is also O(n) due to the call stack depth required to store the intermediate function calls. The invariant is that `recursiveFactorial(k)` correctly computes `k!` for all `k` from `n` down to 0.

Pseudocode:

function recursiveFactorial(n):
  if n < 0:
    error 'Factorial not defined for negative numbers'
  if n == 0:
    return 1
  else:
    return n * recursiveFactorial(n - 1)