Factorial Recursion

Ayumi Tanaka
Algorithm Novice
Published in
1 min readOct 1, 2020

Q. Write an algorithm that is the factorial function with recursion.

const factorial = function (x) { if (x === 0) return 1; else return x * factorial(x-1);}
console.log(factorial(5)); // should be 120 = 5 * 4 * 3 * 2 * 1
  1. If x === 0, return 1.
  2. Otherwise, return x * factorial(x-1).
x = 5
? x === 0 // False
5 * factorial(4)
x = 4
? x === 0 // False
4 * factorial(3)
...x = 1
? x === 0 // False
1 * factorial(0)
x = 0
? x === 0 // True //1
120 = 5 * 4 * 3 * 2 * 1

--

--