Skip to content
DSA in JavaScript
Recursion & Backtracking

Factorial

Algorithm · Starter

Level: StarterNumber Theory

Step through it: Number Theory pattern

a, b
48
18

Step 1 of 5

Goal: the greatest common divisor of 48 and 18. Key fact: the answer stays the same if you replace (a, b) with (b, the remainder of a ÷ b). The numbers shrink quickly.

In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example:

5! = 5 * 4 * 3 * 2 * 1 = 120
nn!
01
11
22
36
424
5120
6720
75 040
840 320
9362 880
103 628 800
1139 916 800
12479 001 600
136 227 020 800
1487 178 291 200
151 307 674 368 000

Code

factorial.js
/**
 * @param {number} number
 * @return {number}
 */
export default function factorial(number) {
  let result = 1;

  for (let i = 2; i <= number; i += 1) {
    result *= i;
  }

  return result;
}
factorialRecursive.js
/**
 * @param {number} number
 * @return {number}
 */
export default function factorialRecursive(number) {
  return number > 1 ? number * factorialRecursive(number - 1) : 1;
}

References

Wikipedia

Practice

Spotted a mistake or something unclear? Report it on GitHub.

On this page