Multiply Every Integer From 1 Through N

Solve this Problem
Easy10–15 min
Topics
Companies
Practice:GFG ↗
Given a non-negative integer n, compute the product of every integer from 1 up to n (with the standard convention that the product for n=0 is 1). A single loop with a running product handles this directly, using no extra memory beyond the running total itself. The recursive framing expresses the same idea differently: the answer for n is just n multiplied by the answer for n-1, bottoming out once n reaches 1 or 0. Both do the same amount of multiplication — the difference is that recursion pays for it in stack frames: every call waits, paused, for the one below it to finish, so at the deepest point of the recursion there are n frames alive at once, where the loop only ever needed a single variable.

Test Case 1:

Input:n = 6
Output:720
Explanation:6×5×4×3×2×1 = 720.

Test Case 2:

Input:n = 9
Output:362880
Explanation:9×8×7×...×1 = 362880.

Test Case 3:

Input:n = 12
Output:479001600
Explanation:The largest value tested here, still comfortably within a 32-bit signed integer.

Constraints

  • 0 ≤ n ≤ 12
  • 0! is defined as 1, matching the standard mathematical convention
🚀

Try the Dry Run

Don't just read the solution — watch it execute, one step at a time.

Approach & Solutions

Iterative — Single Loop

Optimal

Start a running product at 1 and multiply it by every integer from 2 up to n in a single loop. This is the most direct way to compute the result — no function-call overhead, and the amount of extra memory used never grows, regardless of how large n is.

TimeO(n)
SpaceO(1)
1class Solution { 2 public int computeFactorial(int n) { 3 int result = 1; 4 for (int i = 2; i <= n; i++) { 5 result *= i; 6 } 7 return result; 8 } 9}

Recursive — n × factorial(n − 1)

Good

Define the answer in terms of a smaller version of itself: the product of every integer from 1 to n equals n times the product of every integer from 1 to n-1. The base case (n ≤ 1) is where the recursion bottoms out and returns 1 directly. Every recursive call adds a frame to the call stack, so — unlike the loop — the memory used here genuinely grows with n, even though the amount of arithmetic work is the same either way.

TimeO(n)
SpaceO(n) call-stack space
1class Solution { 2 public int computeFactorial(int n) { 3 if (n <= 1) return 1; 4 return n * computeFactorial(n - 1); 5 } 6}

Related Problems