InterviewPrepKit

Home / Coding / Math & Geometry

Factorial Trailing Zeroes

medium Original ↗
Solving tips
  • A trailing zero is a factor of 10 = 2 x 5; since factors of 2 are far more plentiful, the count of 5s is the limiting factor.
  • Use Legendre's formula: answer = n//5 + n//25 + n//125 + ... until the term hits 0.
  • Don't forget higher powers of 5: multiples of 25 contribute a second 5, multiples of 125 a third, and so on.
  • Never build n! itself; the formula runs in O(log_5 n) time and O(1) space.

Problem

Given an integer n, return the number of trailing zeros in n! (n factorial, n! = 1 · 2 · 3 · ... · n). A trailing zero is a 0 at the end of the number; for example, 100 has two trailing zeros. Do it without actually computing the (astronomically large) factorial.

Examples

  • n = 303! = 6 has no trailing zero.
  • n = 515! = 120 ends in one zero.
  • n = 25625! ends in six zeros (25 contributes two factors of 5, plus one each from 5, 10, 15, 20).

Constraints

  • 0 <= n <= 10^4

Think about it first

Hint 1 A trailing zero comes from a factor of 10, and every 10 is a 2 × 5. So the number of trailing zeros equals the number of times 10 divides the factorial — i.e. `min(count of factor 2, count of factor 5)`.
Hint 2 Among `1..n`, factors of 2 are far more common than factors of 5. So the count of 5s is always the limiting factor — you only need to count how many 5s appear in the prime factorization of `n!`.
Hint 3 Multiples of 5 each give one 5, multiples of 25 give an extra one, multiples of 125 yet another, and so on. The answer is `n//5 + n//25 + n//125 + ...` until the term becomes 0.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.