Given a non-negative integer n, compute n! (n factorial). Input: one integer…

2025

Given a non-negative integer n, compute n! (n factorial).

Input: one integer n, where 0 ≤ n ≤ 12.

Output: the value of n!.

Example 1

Input: 5

Output: 120

Explanation: 1 × 2 × 3 × 4 × 5 = 120.

Example 2

Input: 4

Output: 24

Explanation: 1 × 2 × 3 × 4 = 24.

Attempted by 10 students.

Show answer & explanation

Concept

For a non-negative integer n, the factorial n! is the product of all positive integers from 1 through n. By definition, 0! = 1.

An iterative algorithm maintains a running product. Starting from 1 is essential because 1 is the multiplicative identity, so it does not change the product.

Application

  1. Read n and initialize result = 1.

  2. For each integer i from 2 through n, update result = result × i.

  3. Print result. If n is 0 or 1, the loop performs no multiplication and the initialized value 1 is printed.

Trace for n = 5 (result starts at 1):

  1. i = 2: result = 1 × 2 = 2

  2. i = 3: result = 2 × 3 = 6

  3. i = 4: result = 6 × 4 = 24

  4. i = 5: result = 24 × 5 = 120

The algorithm uses O(n) time and O(1) extra space.

Cross-check

For n = 4, the same process gives 1 × 2 × 3 × 4 = 24, matching the sample output. For n = 0, it returns 1, matching the definition of 0!.

Explore the full course: Coding For Placement

Loading lesson…