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.
Step-by-step:
-
238 / 5 = 47
→ 47 numbers divisible by 5 → contribute 1 five
👉count = 47
-
47 / 5 = 9
→ 9 numbers divisible by 25 → contribute 2 fives
👉count = 47 + 9 = 56
-
9 / 5 = 1
→ 1 number divisible by 125 → contributes 3 fives
👉count = 56 + 1 = 57
-
1 / 5 = 0
→ loop ends
✅ Total trailing zeroes = 57
🧠Final Table:
Division | Result | Meaning |
---|---|---|
238 / 5 | 47 | Numbers divisible by 5 (1× 5s) |
238 / 25 | 9 | Numbers divisible by 25 (2× 5s) |
238 / 125 | 1 | Numbers divisible by 125 (3× 5s) |
238 / 625 | 0 | Stop (no more 5s) |
Total | 57 | Trailing zeroes in 238! |
⏱ Time & Space Complexity
-
Time:
O(log₅ n)
-
Space:
O(1)
(no extra space used)
Comments
Post a Comment