Tutorialspoint
Problem
Solution
Submissions

Calculate Factorial

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a JavaScript program to calculate the factorial of a given non-negative integer. The factorial of a number n (denoted as n!) is the product of all positive integers less than or equal to n. By definition, 0! = 1.

Example 1
  • Input: n = 5
  • Output: 120
  • Explanation:
    Factorial of 5 means 5! = 5 × 4 × 3 × 2 × 1. Calculate step by step: 5 × 4 = 20, 20 × 3 = 60, 60 × 2 = 120, 120 × 1 = 120. Therefore, 5! = 120.
Example 2
  • Input: n = 0
  • Output: 1
  • Explanation: By mathematical definition, 0! = 1. This is a special case in factorial calculation. Therefore, 0! = 1.
Constraints
  • 0 ≤ n ≤ 12
  • The input will always be a non-negative integer
  • Handle the special case where n = 0
  • Time Complexity: O(n)
  • Space Complexity: O(1) for iterative approach
NumberControl StructuresIBMSwiggy
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Handle the base case where n equals 0, which should return 1
  • Use an iterative approach starting from 1 and multiply by each number up to n
  • Initialize a result variable to 1 and multiply it by numbers from 1 to n
  • Alternatively, you can use a recursive approach with proper base case handling
  • Make sure to handle edge cases like n = 0 and n = 1

Steps to solve by this approach:

 Step 1: Check if the input number n is 0 or 1, and return 1 for these base cases.
 Step 2: Initialize a result variable to 1 to store the factorial value.
 Step 3: Create a loop starting from 2 and going up to n (inclusive).
 Step 4: In each iteration, multiply the result by the current loop counter value.
 Step 5: Continue the multiplication process until the loop reaches n.
 Step 6: Return the final result which contains the factorial of n.
 Step 7: The iterative approach ensures O(n) time complexity and O(1) space complexity.

Submitted Code :