The factorial of a non-negative number,n, is computed as the product of all integers between 1 and n (both inclusive).
It can also be thought of as:
Note: The factorial of 0 is 1.
There are two ways to compute the factorial of a number in JavaScript.
Both of these approaches will be explored below.
Keeping in mind the first definition of a factorial, the variable i
is initially set equal to n
and is gradually decremented to 1. In each step, the result of the multiplication is stored in the variable answer
.
The table below shows how the values of i
and answer
vary with each iteration.
i |
answer |
---|---|
4 | 4 |
3 | 4 * 3 = 12 |
2 | 12 * 2 = 24 |
1 | 24 * 2 = 1 |
Pro: Takes less memory than the recursive implementation.
Con: The code is lengthier than that of the recursive implementation.
function factorial(n){let answer = 1;if (n == 0 || n == 1){return answer;}else if(n > 1){for(var i = n; i >= 1; i--){answer = answer * i;}return answer;}else{return "number has to be positive."}}let n = 4;answer = factorial(n)console.log("Factorial of " + n + " : " + answer);
As stated above, the factorial of n
can be found by finding the factorial of a number one less than n
, and then multiplying this answer with n
. So the factorial of n-1 can be thought of as a subproblem that needs to be computed first.
The table below shows the value returned by each function call.
function call | return value |
---|---|
factorial(1) | 1 (base case) |
factorial(2) | 2 * 1 = 2 |
factorial(3) | 3 * 2 = 6 |
factorial(4) | 4 * 6 = 24 |
Pro: Shorter and cleaner code.
Con: Greater memory requirements as all the function calls remain on the stack until the base case is reached.
function factorial(n){if(n < 0){return "number has to be positive."}//base caseif(n == 0 || n == 1){return 1;//recursive case}else{return n * factorial(n-1);}}let n = 4;answer = factorial(n)console.log("Factorial of " + n + " : " + answer);
Free Resources