Problem
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.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Constraints:
0 <= n <= 18
Solution
Method 1 – Iterative Generator
Intuition
A factorial sequence is a cumulative product sequence. We can yield each factorial by multiplying the previous result by the next integer, starting from 1.
Approach
- Initialize a variable
ans
to 1. - For each integer
i
from 1 ton
:- Multiply
ans
byi
. - Yield
ans
.
- Multiply
- The generator yields the factorial sequence up to
n!
.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, since we compute each factorial up to n. - 🧺 Space complexity:
O(1)
, only a constant amount of space is used for variables.