Example #1: The factorial: \( n! \) is the product of all positive integers less than or equal to \( n \) and has a natural recursive definition in mathematics. This function is defined by two rules: the $2$ base cases \( 0! = 1 \) and $1! = 1$ and the recursive step \( n! = n \cdot (n - 1)! \), which reduces the input size by 1 at each call.
For instance, to compute \( 4! \), we evaluate $4 \cdot 3! \;$$= 4 \cdot 3 \cdot 2! \;$$= 4 \cdot 3 \cdot 2 \cdot 1! \;$$= 4 \cdot 3 \cdot 2 \cdot 1 \;$$= 24$.
Although this function can also be computed iteratively with a loop, the recursive version mirrors the mathematical definition more directly and is easier to reason about for small inputs. Nevertheless, for large \( n \), recursive calls may lead to performance issues or stack overflow unless optimized using techniques like memoization or tail recursion.
Here is the recursive formula/definition: \( n! = \begin{cases} 1 & \text{if } n = 0 \\ n \cdot (n-1)! & \text{if } n > 0 \end{cases} \)
(
$$n! = \begin{cases} 1 & \text{if } n = 0 \\ n \cdot (n-1)! & \text{if } n > 0 \end{cases}$$
)