basics · beginner · ~15 min

Factorial

Use a loop to accumulate a product.

Challenge

Compute n! = 1 * 2 * ... * n with a loop.

Task

Implement unsigned long factorial(int n) that returns the factorial of n. No main — the grader calls it.

Input

One int argument n with n >= 0. You may assume the result fits in unsigned long.

Output

The product 1 * 2 * ... * n as an unsigned long. By definition factorial(0) is 1.

Example

factorial(0)   ->   1
factorial(5)   ->   120
factorial(10)  ->   3628800

Edge cases

  • factorial(0) and factorial(1) are both 1.
  • Factorials grow fast — only inputs whose result fits in unsigned long are tested.

Why this matters

Factorial is the simplest non-trivial recursive-or-iterative function. It also overflows fast — 13! overflows int — making it a great teaching example for integer-size choice.

Input format

One int argument n with n >= 0.

Output format

The factorial of n as an unsigned long; factorial(0) is 1.

Constraints

Assume the result fits in unsigned long.

Starter code

unsigned long factorial(int n) {
    /* TODO */
    return 0;
}

Common mistakes

Returning int (overflows at 13!). Forgetting the 0! = 1 base case. Iterating from 0 instead of 1 (multiplies by 0).

Edge cases to handle

0! must be 1 (by convention). Large n overflows unsigned long long at 21!.

Complexity

O(n) iterative, O(n) stack depth recursive.

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.