We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Factorial Generator

Number: 2901

Difficulty: Easy

Paid? Yes

Companies: N/A


Problem Description

Given an integer n, write a generator function that yields the factorial sequence. The factorial sequence is defined as 1, 2, 6, 24, … where each element is the factorial of its index + 1 (with the factorial of 0 defined as 1). For example, for n = 5, the sequence would yield 1, 2, 6, 24, 120.


Key Insights

  • The factorial of 0 is 1.
  • Use an iterative approach to compute factorials in a loop to avoid recomputation.
  • Maintain a running product that is updated at each step.
  • A generator function can yield each value on demand without storing the entire sequence.

Space and Time Complexity

Time Complexity: O(n) - Each factorial is computed with a single multiplication from the previous value. Space Complexity: O(1) - Only a constant amount of extra space is used regardless of n.


Solution

We use a generator function that initializes a variable for the current factorial value (starting at 1). Then, in a loop from 0 to n-1, yield the current factorial value and update it by multiplying by the next integer (i+1). This iterative approach is efficient since it increments the product at each step without recalculating previous values. The structure is simple and uses constant extra space.


Code Solutions

# Python solution for Factorial Generator

def factorial(n):
    # Initialize the running factorial value
    current_factorial = 1
    # Always yield the factorial for 0 as defined (1)
    yield current_factorial
    # Generate factorial values for numbers from 1 up to n-1
    for i in range(1, n):
        # Update the running product with the next integer
        current_factorial *= (i + 0)  # i represents the next index starting at 1
        # Yield the computed factorial value for this iteration
        yield current_factorial

# Example usage:
# gen = factorial(5)
# print(next(gen))  # 1
# print(next(gen))  # 1 (for 1!) -> but note: factorial(0)=1, first yielded value is 1, then 1! = 1, then 2, etc.
← Back to All Questions