Recursion - Factorial

By on

(n!)

Factorial is the product of a number and all the numbers below it. Only applicable to regular numbers (positive integers).

For example, factorial 4, which is written also as 4! is equal to 24.

So: 4 x 3 x 2 x 1 = 24

Let’ solve this factorial problem in two ways, one without using recursion:

function factorial(num) {
  var result = 1;
  for (var i = 1; i <= num; i++) {
    result *= i;
  }

  return result;
}

Now let’s solve it using recursion. Recursion needs a base case, so in this problem, where 0! or 1!, we need to return 1.

function factorial(num) {
	if (num <= 1) {
    	return 1;
	}
	
	return num * factorial(num - 1);
}

Notice that factorial(num) function is used in the function again, this is where recursion is happening. The function is being called inside the function.

Since 4! is 4 x 3! (see Recursive factorial - Khan Academy for more explanation), this function is solving it recursively, num x factorial(num-1), calling the function over and over inside factorial(num) until num is equal to 0 or 1.

notes

Visuals help, natashatherobot draws a diagram of the recursive function for factorial on her blog: Inception All Over Again: Recursion, Factorials, And Fibonacci In Ruby - natashatherobot

Here’s an excellent video explaning factorial: Evaluating Factorials! Basic Info

Another video comparing recursive and iterative factorial functions by Khan Academy: comparing recursive and iterative factorial functions by Khan Academy

Why does 0 factorial equal 1?

<p class=store> Please hit me up on twitter for feedback </p>