Mar 15 2021
Last night, I was on HackerRank solving some problems, and I came across a simple factorial problem.
Here’s how I solved it:
function factorialIterative(n) {
let result = 1;
for (let i = 1; i <= n; i++) {
*= i;
result
}return result;
}
While this solution works, I wanted to explore solving the problem using recursion.
After spending some time with friends trying to wrap my head around recursion, I finally got it!
function factorialRecursive(n) {
if (n <= 1) {
return 1;
}return n * factorialRecursive(n - 1);
}
Let’s say n
is 4. Here’s how the function works
step-by-step:
4 * factorial(3)
.factorial(3)
, it calls itself with
3
.factorial(3)
returns
3 * factorial(2)
.factorial(2)
returns
2 * factorial(1)
.factorial(1)
returns 1
, which is the base
case.Now that we’ve reached the base case, the function works its way back up:
factorial(2)
becomes 2 * 1 = 2
.factorial(3)
becomes 3 * 2 = 6
.factorial(4)
becomes 4 * 6 = 24
.The final result is 24.
Note: This is just a high-level explanation to help me understand recursion better.
re-edited Jan 6 2025