Open In App
Related Articles

Factorial of a number using JavaScript

Improve Article
Improve
Save Article
Save
Like Article
Like

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 factorial of n is represented by n!. 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

  • 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: 

Javascript




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

Since the code is running for all the values of n, Time Complexity: O(n):

As we are not allocating any extra space for a variable so the Auxiliary Space: O(1): 

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: 

Javascript




let n = 5;
function factorial(n) { 
    if (n === 0) { 
        return 1; 
    
    else
        return n * factorial( n - 1 ); 
    
  
console.log(factorial(n));

Output

120

Since the code is running for all the values of n, Time Complexity: O(n)

As the stack is being created for each function call, so Auxiliary Space: O(n)


Last Updated : 23 Jun, 2023
Like Article
Save Article
Similar Reads
Related Tutorials