AlgoViz

See it run

Build 5! one multiplication at a time, count the fives hiding in 25!, watch n! leave 2^n behind, and see how close Stirling's formula gets.

Operations

Factorial Calculator

$n! = 1 \times 2 \times \dots \times n$, the number of ways to arrange $n$ distinct items. Here we build $5!$ with one running product, one multiplication per number.

Step 1 of 8

Compute 5! (5 factorial)

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
i = -result = 1multiplications = 0

5! = 1 \times 2 \times 3 \times 4 \times 5. We keep one running product, result, and start it at 1: the empty product, which is also 0! = 1. This answers the question: in how many ways can 5 distinct items be arranged?

Step 1: Compute 5! (5 factorial)

def factorial(n):    if n < 0:        raise ValueError("n must be non-negative")    result = 1                  # 0! = 1, the empty product    for i in range(2, n + 1):        result *= i             # result is now i!    return resultprint(factorial(3))   # 6 arrangements of 3 booksprint(factorial(5))   # 120print(factorial(0))   # 1
Time
O(n) multiplications
Space
O(1) extra
recursive version
O(n) call stack
math.factorial
built in, fastest

Start the product at 1, not 0, and loop up to n inclusive with range(2, n + 1). In Python, math.factorial(n) does the same thing faster.

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Starting the product at 0

    critical

    Anything times 0 is 0, so every factorial comes out as 0. The empty product is 1, which is also why 0! = 1.

    Wrong
    result = 0for i in range(1, n + 1):    result *= i      # always 0
    Right
    result = 1          # empty productfor i in range(2, n + 1):    result *= i
  • Stopping one short with range(1, n)

    major

    range stops before its end value, so range(1, n) never multiplies by n and returns (n - 1)! instead of n!.

    Wrong
    for i in range(1, n):       # misses n    result *= i
    Right
    for i in range(2, n + 1):   # includes n    result *= i
  • Counting only multiples of 5

    critical

    25, 50, 75 and 100 each hold two fives, and 125 holds three. n // 5 alone gives 20 for 100!, but the true answer is 24.

    Wrong
    def trailing_zeroes(n):    return n // 5            # 20 for n = 100
    Right
    def trailing_zeroes(n):    count, power = 0, 5    while power <= n:        count += n // power        power *= 5    return count             # 24 for n = 100
  • Building n! just to count its zeros

    major

    n! has about n log10 n digits, so building it and scanning the string is slow and, in fixed-width languages, overflows long before the answer. The 5-counting loop is O(log n).

    Wrong
    s = str(math.factorial(n))zeros = len(s) - len(s.rstrip("0"))
    Right
    zeros = trailing_zeroes(n)   # sum of n // 5**i
  • Ignoring overflow in fixed-width languages

    major

    13! does not fit in a 32-bit int and 21! does not fit in a 64-bit long. The value wraps around with no error. Python is safe, but interview answers in Java or C++ are not.

    Wrong
    // Java: int f = 1;// for (int i = 2; i <= 13; i++) f *= i;   // wrong, overflowed
    Right
    # Python ints never overflow; in Java use BigInteger,# or reduce mod 10**9 + 7 at every step if the problem asksMOD = 10**9 + 7f = 1for i in range(2, n + 1):    f = f * i % MOD
  • Deep recursion for factorial

    minor

    The recursive version is elegant, but Python's default recursion limit is about 1,000, so factorial(5000) crashes. A loop does the same work in O(1) extra space.

    Wrong
    def fact(n):    return 1 if n <= 1 else n * fact(n - 1)fact(5000)          # RecursionError
    Right
    import mathmath.factorial(5000)  # fine, and fast

Interview tips

  • Spot it fast

    • Counting arrangements, orderings or permutations of n distinct things.
    • Trailing zeros of n! or divisibility of n! by a prime: count prime factors, never build n!.
    • nCr or nPr asked modulo 10^9 + 7: precompute factorials and inverse factorials.
    • Trying every ordering is O(n!), only safe up to about n = 10.
  • Numbers to know cold

    • 5! = 120, 10! = 3,628,800.
    • 12! is the last to fit int32, 20! the last to fit int64.
    • Z(25) = 6, Z(100) = 24, Z(1000) = 249.
    • n! passes 2^n at n = 4 and never looks back.
  • Say it in the interview

    • "Each zero needs a 2 and a 5. There are always more 2s, so I count 5s: n/5 + n/25 + n/125 and so on."
    • "The loop runs once per power of 5, so it is O(log n) time and O(1) space."
    • "log(n!) is Theta(n log n), which is where the sorting lower bound comes from."
  • Traps

    • 0! is 1, not 0.
    • n // 5 alone misses the extra fives in 25, 125, 625.
    • In Java and C++, factorials overflow silently from 13! (int) and 21! (long).