Code Logo

Factorial

Published at25 Jul 2026
Basic Operations Easy 0 views
Like0

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

Example 1
Input
1
Output
1
Explanation

1! = 1

Example 2
Input
7
Output
5040
Explanation

7! = 5040

Example 3
Input
3
Output
6
Explanation

3! = 6

Example 4
Input
5
Output
120
Explanation

5! = 5*4*3*2*1

Example 5
Input
0
Output
1
Explanation

0! = 1

Algorithm Flow

Recommendation Algorithm Flow for Factorial
Recommendation Algorithm Flow for Factorial

Solution Approach

Use a loop to multiply numbers from 2 to n into an accumulator.

function solution(n) {
  var r = 1;
  for (var i = 2; i <= n; i++) r *= i;
  return r;
}

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

java
class Solution {
    public int solution(int n) {
        int r=1;for(int i=2;i<=n;i++)r*=i;return r;
    }
}