
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
Editorial
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. |
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