What it teaches: Count factors of 5 instead of computing n!.
Practise it on judges as “Factorial Trailing Zeroes”.
In plain words
Every zero at the end of a number comes from a 10, and 10 = 2 × 5. In n! there are always more 2s than 5s, so just count the 5s: one from every multiple of 5, one more from every multiple of 25, and so on.
Return the number of trailing zeros of n!. Example: n = 5 → 1 (5! = 120).
The problem
Return the number of trailing zeros in n!.
Example 1
Input: n = 5
Output: 1
5! = 120.
Constraints
0 ≤ n ≤ 10⁴
Pattern clues in the wording
→ Zeros at the end of a huge product
These clues point to Number Theory and Combinatorics: GCD, primes, modular arithmetic, fast power and counting formulas that turn loops into a few lines of math.
Stuck? Take one hint at a time
Solution · starter
class Solution {
public int trailingZeroes(int n) {
return 0;
}
}
Write your solution locally or in your editor for now. Pick Java, Python, C++, JavaScript or Go above: every solution on this page switches with it. The in-browser runner will run these tests right here.