Factorial Generator Problem
#2803
Description
LeetCode Problem 2803.
Write a generator function that takes an integer n as an argument and returns a generator object which yields the factorial sequence.
The factorial sequence is defined by the relation n! = n * (n-1) * (n-2) * ... * 2 * 1.
The factorial of 0 is defined as 1.
Example 1:
Input: n = 5
Output: [1,2,6,24,120]
Explanation:
const gen = factorial(5)
gen.next().value // 1
gen.next().value // 2
gen.next().value // 6
gen.next().value // 24
gen.next().value // 120
Example 2:
Input: n = 2
Output: [1,2]
Explanation:
const gen = factorial(2)
gen.next().value // 1
gen.next().value // 2
Example 3:
Input: n = 0
Output: [1]
Explanation:
const gen = factorial(0)
gen.next().value // 1
Constraints:
0 <= n <= 18
Solution
Approach: Keep a running product
Each factorial is the previous one times i, so a generator only needs one running variable.
- Start with
value = 1and loopifrom1ton: multiply, thenyield. This yields1!, 2!, ..., n!. n = 0must still yield1(the value of0!), and the loop does not run for it, so handle it first.
18! is about 6.4 * 1015, below Number.MAX_SAFE_INTEGER (about 9 * 1015), which is why the limit is 18.
Complexity: Time O(n) overall, space O(1).
/**
* @param {number} n
* @yields {number}
*/
var factorial = function* (n) {
if (n === 0) {
yield 1;
return;
}
let value = 1;
for (let i = 1; i <= n; i++) {
value *= i;
yield value;
}
};