Open In App

Factorial of a number using JavaScript

Given a positive integer n and the task is to find the factorial of that number using JavaScript code. 

For any positive integer ‘n’, the factorial of n is the product of all the values from 1 to n. In mathematics, the factorial of n is represented by n!. a factorial of 0 is 1.



Note: Factorials of negative numbers are not defined as only positive numbers including 0 are defined in the domain of factorials.

JavaScript Program for Factorial

Examples:



Input : 4
Output : 24

Input : 5
Output : 120

Approach 1: Iterative Method

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

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


Article Tags :