Factorial Trailing Zeroes

MediumMath · Prime Factor Counting🧩 Math & GeometryLeetCode #172 ↗Updated

Problem

Given an integer n, return how many zeros appear at the end of n! (n! = 1 × 2 × … × n, with 0! = 1).
Inputn = 3Output0 (3! = 6)
Inputn = 5Output1 (5! = 120)
Inputn = 0Output0

0 ≤ n ≤ 104  ·  Follow-up: solve it in logarithmic time.

Try it yourself

Java
class Solution {
    public int trailingZeroes(int n) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Each trailing zero is a factor 10 = 2 × 5, and factors of 2 are far more common, so just count factors of 5: multiples of 5 give one, multiples of 25 one more, multiples of 125 another… i.e. ⌊n/5⌋ + ⌊n/25⌋ + ⌊n/125⌋ + …
PatternMath & Geometry

Instinct Digits, factors, slopes or distances hide a formula - find the invariant, then guard against overflow, negatives and floating-point error.

Memory hack Mod peels, gcd reduces, squares compare - and long saves the day. Peel digits with %10, reduce slopes with gcd, compare squared distances.

Open the Math & Geometry guide →

Approaches

Brute ForceCompute n! with BigInteger

Time O(n2 log n)Space O(n log n)

Multiply out the full factorial as a big integer (it has O(n log n) digits), then strip zeros by repeatedly dividing by 10 while the remainder is 0. Each of the n multiplications touches every digit.

Java
public int trailingZeroes(int n) {
    BigInteger fact = BigInteger.ONE;
    for (int i = 2; i <= n; i++) fact = fact.multiply(BigInteger.valueOf(i));
    int zeros = 0;
    while (fact.mod(BigInteger.TEN).signum() == 0) {
        fact = fact.divide(BigInteger.TEN);
        zeros++;
    }
    return zeros;
}

Obviously correct, but huge numbers make it slow and memory hungry.

At a glance

LevelApproachTimeSpace
Brute ForceCompute n! with BigIntegerO(n2 log n)O(n log n)
BetterCount Factors of 5 in Every Multiple of 5O(n log n)O(1)
OptimalLegendre's Formula (Divide by 5 Repeatedly)O(log n)O(1)
Common pitfalls
  • Computing n! as a long — it overflows at 21!.
  • Counting only n/5 and forgetting extra 5s from 25, 125, …
  • Looping for (p = 5; p <= n; p *= 5) with an int — p can overflow.
Interview tips
  • Explain why 5s, not 2s, are the bottleneck before writing any code.
  • Walk through n = 25 (answer 6) to show why higher powers matter.
  • Name it: this is Legendre's formula for the exponent of a prime in n!.
Pattern
Prime factor counting → questions about zeros/divisibility of n! reduce to counting a prime's exponent with n/p + n/p2 + …
My notes saved in this browser