Skip to main content
Back to problems
#2803
Easy JavaScript

Factorial generator

85.4% acceptance
Apr 1, 2026
20
1
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.

Solution

TypeScript
Time O(n)
Space O(1)
LeetCode
solution.ts
function* factorial(n: number): Generator<number> {
  let fact = 1;
  if (n === 0) {
  yield fact;
  return;
  }
  for (let i = 1; i <= n; i++) {
  fact *= i;
  yield fact;
  }
}

/**
 * const gen = factorial(5);
 * gen.next().value; // 1
 * gen.next().value; // 2
 * gen.next().value; // 6
 * gen.next().value; // 24
 * gen.next().value; // 120
 */