Factorial Generator - Problem
Create a generator function that produces the factorial sequence! ๐ข
Given an integer n, your generator should yield factorials starting from 0! up to n!. The factorial of a number k is defined as:
0! = 1(by definition)k! = k ร (k-1) ร (k-2) ร ... ร 2 ร 1for k > 0
Example: For n = 4, your generator should yield: 1, 1, 2, 6, 24 representing 0!, 1!, 2!, 3!, 4!
This problem tests your understanding of generator functions and iterative computation - perfect for building efficient, memory-friendly solutions!
Input & Output
example_1.py โ Basic Case
$
Input:
n = 4
โบ
Output:
[1, 1, 2, 6, 24]
๐ก Note:
Generator yields 0!=1, 1!=1, 2!=2, 3!=6, 4!=24 in sequence
example_2.py โ Edge Case Zero
$
Input:
n = 0
โบ
Output:
[1]
๐ก Note:
Only yields 0! = 1 by mathematical definition
example_3.py โ Small Sequence
$
Input:
n = 2
โบ
Output:
[1, 1, 2]
๐ก Note:
Yields factorials: 0!=1, 1!=1, 2!=2ร1=2
Constraints
- 0 โค n โค 18
- Generator must yield exactly n+1 values
- Important: 0! = 1 by mathematical convention
- Results may become very large (18! = 6.4 ร 1015)
Visualization
Tap to expand
Understanding the Visualization
1
Foundation
Start with factorial = 1 (representing 0!)
2
Build Up
For each new level i, multiply current height by i
3
Yield Result
Report the new tower height (factorial value)
4
Continue
Repeat until we reach level n
Key Takeaway
๐ฏ Key Insight: Rather than recalculating each factorial from scratch (O(nยฒ)), we can build each factorial from the previous one using the relationship n! = (n-1)! ร n, achieving optimal O(n) time complexity.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code