Iterative vs Recursive Solutions for Calculating Factorials

↩︎ Mustafa Ozturk

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++) { 
    result *= i; 
  }
  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:

  1. The function calculates 4 * factorial(3).
  2. To calculate factorial(3), it calls itself with 3.
  3. Similarly:

Now that we’ve reached the base case, the function works its way back up:

The final result is 24.

Note: This is just a high-level explanation to help me understand recursion better.


re-edited Jan 6 2025