KatInterview

Factorial Trailing Zeros Without Building the Factorial

Math & Bit ManipulationAuto-graded · 20 test cases
EasyAuto-gradedMath & Bit Manipulationmathnumber-theoryfactorial

Last updated

Count the base-10 trailing zeros of n! by tallying factors of 5, never constructing the enormous factorial itself.

Implement a function trailing_zeros(n) that returns how many zeros sit at the end of the base-10 representation of n! (n factorial).

You must not build n! explicitly — for large n it has far too many digits. Instead, reason about how many times 10 divides the product.

Rules:

  • Each trailing zero comes from teaming up one factor of 2 with one factor of 5. In n!, factors of 2 are plentiful, so the answer equals the number of times 5 divides n!.
  • For n = 0 or n = 1, return 0 (both 0! and 1! equal 1).
  • For any n < 0, return 0 as well — the factorial is undefined, but do not raise an exception.
  • The answer must be exact, including values like 25, 125, and 625, which supply more than one factor of 5 each.

Constraints

  • n is an integer.
  • -10^18 <= n <= 10^18 (values may be very large; never construct n!).
  • The function should run in time proportional to log₅(max(n, 1)).
  • Return an int.

Examples

Example 1

Input: trailing_zeros(0)

Output: 0

Example 2

Input: trailing_zeros(5)

Output: 1

Example 3

Input: trailing_zeros(10)

Output: 2

Example 4

Input: trailing_zeros(25)

Output: 6

Hints

Hint 1

A trailing zero needs one 2 and one 5 — which of the two runs out first inside n!?

Hint 2

Add up the count of multiples of 5, then multiples of 25, then 125, and so on.

Hint 3

Repeatedly divide n by 5 and add each quotient to your total; stop once the quotient becomes 0.