Factorial Generator - 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.

The generator should yield factorials starting from 0! up to n!.

Input & Output

Example 1 — Basic Case
$ Input: n = 4
Output: [1, 1, 2, 6, 24]
💡 Note: Generate factorials from 0! to 4!: 0!=1, 1!=1, 2!=2, 3!=6, 4!=24
Example 2 — Minimum Case
$ Input: n = 0
Output: [1]
💡 Note: Only 0! = 1 by definition
Example 3 — Small Sequence
$ Input: n = 2
Output: [1, 1, 2]
💡 Note: Generate 0!=1, 1!=1, 2!=2×1=2

Constraints

  • 0 ≤ n ≤ 10
  • All factorials will fit in 32-bit integer

Visualization

Tap to expand
Factorial Generator Optimized - Incremental Calculation INPUT Parameter: n = 4 n = 4 Generate factorials for: 0 1 2 3 4 0! , 1! , 2! , 3! , 4! Generator Yields values lazily ALGORITHM STEPS 1 Initialize Set factorial = 1 2 Yield 0! yield 1 (base case) 3 Loop i: 1 to n Iterate through range 4 Update and Yield factorial *= i, yield Incremental Calculation: i=0: fact=1 yield 1 i=1: fact=1*1=1 yield 1 i=2: fact=1*2=2 yield 2 i=3: fact=2*3=6 yield 6 i=4: fact=6*4=24 yield 24 FINAL RESULT Generated Factorial Sequence: 0! 1 1! 1 2! 2 3! 6 4! 24 Output Array: [1, 1, 2, 6, 24] OK - 5 values generated Verification: 0! = 1 1! = 1 2! = 2 x 1 = 2 3! = 3 x 2 x 1 = 6 4! = 4 x 3 x 2 x 1 = 24 Key Insight: Instead of recalculating each factorial from scratch (n! = n * (n-1) * ... * 1), we use incremental calculation: each factorial is just the previous one multiplied by the current number (n! = (n-1)! * n). This reduces complexity from O(n^2) to O(n) and generators yield values lazily for memory efficiency. TutorialsPoint - Factorial Generator | Optimized - Incremental Calculation
Asked in
Google 15 Amazon 12 Microsoft 8
22.1K Views
Medium Frequency
~15 min Avg. Time
850 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