Factorial
Compute the factorial of a non-negative integer n, denoted n!. The factorial is defined as the product of all positive integers from 1 to n. By definition, 0! = 1.
For example, 5! = 5 × 4 × 3 × 2 × 1 = 120. 3! = 6. 1! = 1. 0! = 1. Factorials grow extremely fast — 10! is already 3,628,800. The input is guaranteed to be small enough that the result fits within a 32-bit integer (n ≤ 12).
The factorial function is fundamental to combinatorics (counting permutations and combinations), probability theory, and algorithm analysis. It appears in calculating binomial coefficients, the number of ways to arrange items, and the runtime of certain algorithms like bogosort. Understanding how to compute a factorial iteratively builds a foundation for understanding loops and accumulation patterns.
The simplest implementation uses a loop that multiplies a running product by each integer from 2 up to n. Starting the product at 1 handles both n = 0 (loop never runs, returns 1) and n = 1 (loop never runs, returns 1 correctly since 1! = 1).
Alternative approaches include recursion (n * factorial(n-1)) and the use of built-in product functions. The iterative approach is preferred because it avoids stack overflow and is generally faster.
Example Input & Output
1! = 1
7! = 5040
3! = 6
5! = 5*4*3*2*1
0! = 1
Algorithm Flow

Solution Approach
Use a loop to multiply numbers from 2 to n into an accumulator.
Initialize the result r to 1. Loop i from 2 up to n, multiplying r by i at each step. After the loop, return r. For n = 0 or n = 1, the loop never executes and r stays 1, correctly giving 0! = 1 and 1! = 1.
In languages with functional programming features, you can use a product or reduce operation: Python's math.prod(range(1, n+1)), Rust's (1..=n).product(), or JavaScript's array reduce. These express the same logic more declaratively.
Time complexity is O(n), space complexity is O(1).
Best Answers
class Solution {
public int solution(int n) {
int r=1;for(int i=2;i<=n;i++)r*=i;return r;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
