Multiply Every Integer From 1 Through N
Solve this Problemn, 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:
Test Case 2:
Test Case 3:
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
OptimalStart 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.
O(n)O(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)
GoodDefine 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.
O(n)O(n) call-stack space1class Solution {
2 public int computeFactorial(int n) {
3 if (n <= 1) return 1;
4 return n * computeFactorial(n - 1);
5 }
6}