InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Math & Geometry

Factorial Trailing Zeroes

medium Original ↗ 00:00

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 computing the factorial itself, which grows very large.

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug