Factorial Trailing Zeroes LeetCode

Given an integer n, return the number of trailing zeroes in n!.


Note that n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1.


 


Example 1:


Input: n = 3

Output: 0

Explanation: 3! = 6, no trailing zero.

Example 2:


Input: n = 5

Output: 1

Explanation: 5! = 120, one trailing zero.

Example 3:


Input: n = 0

Output: 0


🤔 What is a trailing zero?

A trailing zero is a 0 at the end of a number.

Example:

  • 100 has 2 trailing zeroes

  • 1200 has 2 trailing zeroes

  • 5040 has 1 trailing zero

  • 6 has no trailing zeroes



A trailing zero is created when a number is divisible by 10, which comes from 2 × 5.

But in a factorial:

  • We have more 2s than 5s.

  • So, the number of 5s in the factorization determines the number of trailing zeroes.

 Optimal Approach (Using Division by Powers of 5)

Instead of computing factorial (which overflows), just count how many 5s are present in n!.

✨ Formula: Trailing zeroes = n/5 + n/25 + n/125 + n/625 + ...

This formula counts:

  • Numbers divisible by 5 (one 5)

  • Numbers divisible by 25 (two 5s)

  • Numbers divisible by 125 (three 5s), etc.


Dry Run for n = 238

int count = 0;
while (n > 0) {
    n /= 5;
    count += n;
}
return count;

Step-by-step:

  1. 238 / 5 = 47 → 47 numbers divisible by 5 → contribute 1 five
    👉 count = 47

  2. 47 / 5 = 9 → 9 numbers divisible by 25 → contribute 2 fives
    👉 count = 47 + 9 = 56

  3. 9 / 5 = 1 → 1 number divisible by 125 → contributes 3 fives
    👉 count = 56 + 1 = 57

  4. 1 / 5 = 0 → loop ends

Total trailing zeroes = 57


🧠 Final Table:

DivisionResultMeaning
238 / 547Numbers divisible by 5 (1× 5s)
238 / 259Numbers divisible by 25 (2× 5s)
238 / 1251Numbers divisible by 125 (3× 5s)
238 / 6250Stop (no more 5s)
Total57Trailing zeroes in 238!


class Solution {
    public int trailingZeroes(int n) {
       
        int count = 0;
while (n > 0) {
    n /= 5;
    count += n;
}
return count;
    }
}

 

⏱ Time & Space Complexity

  • Time: O(log₅ n)

  • Space: O(1) (no extra space used)



Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence