Factorial of a number
JavaScript
easy
15 mins
Examples
Example 1
Input: n = 0 Output: 1
- Explanation: 0! = 1 by definition.
Example 2
Input: n = 4 Output: 24
- Explanation: 4! = 4 × 3 × 2 × 1 = 24
Example 3
Input: n = 6 Output: 720
- Explanation: 6! = 6 × 5 × 4 × 3 × 2 × 1
Constraints
- n must be a non-negative integer
- Large values of n may cause recursion depth issues
- Return false for negative numbers
- Return false for non-integers
- Return false for non-numeric values (NaN, strings, arrays, objects, null, undefined)
Function Signature
function factorial(n) { }
Test Cases
n Expected Output 0 1 1 1 3 6 5 120 7 5040 10 3628800 Invalid inputs → false Examples:
- factorial(-1)
- factorial(2.5)
- factorial("5")
- factorial({})
- factorial([])
- factorial(null)
- factorial(undefined)
Companies:
amazon
capgemini
cisco
tcs
Solve Similar questions 🔥
Want to upskill? Explore our courses!
Namaste DSA
Master DSA from scratch with numerous problems, and expert guidance.
Namaste React
Wanna dive deep into React and become Frontend Expert? Learn with me now!
Namaste Frontend System Design
The most comprehensive and detailed course for frontend system design.
Namaste Node.js
Wanna dive deep into Node.js? Enroll into `Namaste Node.js` now!
