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 ร— 1 for 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
Factorial Tower: Building Each Level10! = 1ร—111! = 1ร—222! = 2ร—363! = 6Key Insight: Running ProductEach factorial = previous factorial ร— current numberTime: O(n) | Space: O(1)
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.
Asked in
Google 25 Amazon 18 Microsoft 15 Meta 12
28.5K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen