Question Bank
JavaScript Factorial: Three Implementations Quiz
Difficulty: Medium
Three seeded ways to compute n! (iterative loop, classic recursion, reduce), plus two companions on memoization and on guarding against negative inputs.
JavaScript Factorial: Three Implementations Quiz
Three seeded ways to compute n! (iterative loop, classic recursion, reduce), plus two companions on memoization and on guarding against negative inputs.
298 views
3
Implement factorial(n) using a for loop. Return 1 for n <= 1 and the product of integers from 2 to n otherwise.
Examples
Example 1:
Input: factorial(0)
Output: 1
Explanation: 0! is defined as 1.Example 2:
Input: factorial(5)
Output: 120
Explanation: 2 * 3 * 4 * 5 = 120.Implement factorial(n) using direct recursion: the base case returns 1 for n <= 1, the recursive case returns n * factorial(n - 1).
Examples
Example 1:
Input: factorial(5)
Output: 120
Explanation: factorial(5) = 5 * factorial(4) = 5 * 24 = 120.Implement factorial(n) using Array.from and reduce: build the range [1..n] and fold it with multiplication, with 1 as the initial accumulator.
Examples
Example 1:
Input: factorial(5)
Output: 120
Explanation: Array.from({length: 5}, (_, i) => i + 1) yields [1, 2, 3, 4, 5], whose product is 120.Add memoization to a recursive factorial so repeated calls reuse prior results across invocations. Use a closed-over Map from n to n!.
Examples
Example 1:
Input: factorial(5); factorial(6)
Output: 120; 720
Explanation: the first call fills the cache up to 5; the second call multiplies cached factorial(5) by 6 instead of recomputing.Make the iterative factorial safe for invalid inputs: throw a TypeError for non-integers and a RangeError for negative integers. Show what factorial(-1) and factorial(2.5) do.
Examples
Example 1:
Input: factorial(-1)
Output: throws RangeError('factorial expects a non-negative integer')
Explanation: factorials are undefined for negative integers, so we reject the input.Example 2:
Input: factorial(2.5)
Output: throws TypeError('factorial expects an integer')
Explanation: 2.5 is not an integer, so Number.isInteger rejects it before any multiplication runs.