Factorialize a Number
Hints
Hint 1
You know your solution should return 1
when the number passed to the function is 0
or 1
. Also, the final value returned will be the product of all the numbers between 1 and the number (inclusive). If you initialize the value for the product to 1
, then think about how you could update this product by multiplying the product by the number in the range.
Hint 2
This problem can be solved with a loop or recursion.
Relevant Links
Solutions
Solution 1 (Click to Show/Hide)
Looping solution
function factorialize(num) {
let product = 1;
for (let i = 2; i <= num; i++) {
product *= i;
}
return product;
}
factorialize(5);
Code Explanation
-
Since the return values for the function will always be greater than or equal to 1,
product
is initialized at one. For the case where the number is0
, the for loop condition will be false, but sinceproduct
is initialized as1
, it will have the correct value when thereturn
statement is executed. -
For all numbers passed to the function which are greater than one, the simple
for
loop will incrementi
by one each iteration and recalculateproduct
up to the valuenum
.
Solution 2 (Click to Show/Hide)
Recursive solution
function factorialize(num) {
if (num <= 0) {
return 1;
}
return num * factorialize(num - 1);
}
factorialize(5);
Code Explanation
Notice at the first line we have the terminal condition, i.e a condition to check the end of the recursion. If num == 0
, then we return 1, i.e. effectively ending the recursion and informing the stack to propagate this value to the upper levels. If we do not have this condition, the recursion would go on until the stack space gets consumed, thereby resulting in a Stack Overflow.
Relevant Links
Solution 3 (Click to Show/Hide)
function factorialize(num, factorial = 1) {
if (num <= 0) {
return factorial;
} else {
return factorialize(num - 1, factorial * num);
}
}
factorialize(5);
Code Explanation
-
In this solution, we use Tail Recursion to optimize the the memory use.
-
In traditional head recursion, the typical model is that you perform your recursive calls first, and then you take the return value of the recursive call and calculate the result. In this manner, you don’t get the result of your calculation until you have returned from every recursive call.
-
In tail recursion, you perform your calculations first, and then you execute the recursive call, passing the results of your current step to the next recursive step. This results in the last statement being in the form of (return (recursive-function params)).
-
In this solution, with each evaluation of the recursive call, the factorial is updated. This is different from the head-recursive solution where all evaluation calculations are stored on the stack until the base case is reached.