Factorial of a number using JavaScript
The factorial of a non-negative integer is the product of all positive integers less than or equal to that number. It’s denoted by “n!” where n is the integer. Factorial represents the number of permutations or arrangements of a set.
Note: Factorials of negative numbers are not defined as only positive numbers including 0 are defined in the domain of factorials.
Examples:
Input : 4
Output : 24
Input : 5
Output : 120
Table of Content
- Approach 1: Iterative Method
- Approach 2: Recursive Method
- Approach 3: Memoization Method
Approach 1: Iterative Method
- Declare a variable with a value of the number whose factorial you have to find.
- Declare a function factorial taking the value as a parameter.
- In the function definition, initialize variable ans to 1.
- Loop in the range of [2, n].
- Multiply ans by the value of i in each iteration.
- Return the value of ans.
Example: In this example, we a following iterative method.
let n = 5;
function factorial(n) {
let ans = 1;
if(n === 0)
return 1;
for (let i = 2; i <= n; i++)
ans = ans * i;
return ans;
}
console.log(factorial(n));
Output
120
Time Complexity: O(n) Since the code is running for all the values of n
Space Complexity: O(1) As we are not allocating any extra space for a variable.
Approach 2: Recursive Method
- Declare a variable with a value of the number whose factorial you have to find.
- Declare a recursive function factorial taking the value as a parameter.
- The function returns 1 if the value is 0 else the return calls the function for value – 1.
- After recursion is over the value returned is the factorial.
Example: In this example, we are following Recursive method
let n = 5;
function factorial(n) {
if (n === 0) {
return 1;
}
else {
return n * factorial( n - 1 );
}
}
console.log(factorial(n));
Output
120
Time Complexity: O(n) Since the code is running for all the values of n
Space Complexity: O(n) As the stack is being created for each function call
Approach 3: Memoization Method
- Declare a variable with the value of the number whose factorial you have to find.
- Declare a function factorial taking the value and a cache (an array to store previously computed results) as parameters.
- If the value is 0, return 1.
- Check if the result for the current value is already stored in the cache. If it is, return the cached result.
- If the result is not cached, calculate the factorial recursively and store the result in the cache.
- Return the result from the cache.
Example: In this example, we follow the memoization method.
let n = 5;
function factorial(n, cache = []) {
if (n === 0) {
return 1;
}
if (cache[n] !== undefined) {
return cache[n];
}
cache[n] = n * factorial(n - 1, cache);
return cache[n];
}
console.log(factorial(n));
Output
120
Time Complexity: O(n) – Each value from 0 to n is computed at most once and stored in the cache.
Space Complexity: O(n) – Due to the recursion stack and the cache array storing results up to n.