Factorial Trailing Zeroes
Medium
Topics
Given an integer n, return the number of trailing zeroes in n! (n factorial).
Example 1
3!, not the zeros anywhere in it. Those factorials grow far past any integer type, so the number itself is never computed — for 3! the answer is 0.Input: n = 3 Output: 0 Explanation: 3! = 6, no trailing zero.
Example 2
Input: n = 5 Output: 1 Explanation: 5! = 120.
Example 3
Input: n = 0 Output: 0
Constraints
- 0 <= n <= 10^4
Editorial — intuition, approach, complexity and pitfalls
Intuition
A trailing zero comes from a factor of 10, and 10 is 2 times 5. In any factorial there are far more factors of 2 than of 5 — every second number contributes a 2, only every fifth a 5 — so the number of 5s is the binding constraint and the answer is simply how many times 5 divides n!.
Counting those is not n / 5, because 25 contributes two 5s, 125 three, and so on. The total is
n/5 + n/25 + n/125 + ... (integer division, until the term is 0)which the loop computes by repeatedly dividing n by 5 and accumulating. Each division counts the multiples of the next power of 5, so a number like 25 is counted once as a multiple of 5 and again as a multiple of 25 — exactly its two factors.
Approach
- While
n > 0: dividenby 5 and add the result to the count.
Dry Run
n = 100
n = 100 // 5 = 20 count 20
n = 20 // 5 = 4 count 24
n = 4 // 5 = 0 count 24, loop ends
answer 24
check: multiples of 5 up to 100 -> 20 of them
of those, multiples of 25 -> 4 extra
total 24 ✓
n = 3 -> 3 // 5 = 0, count 0 (3! = 6, no trailing zero)Complexity
- Time — O(log n) base 5, so a handful of iterations even for huge
n. - Space — O(1).
Common Pitfalls
- Computing
n!and counting zeros. It overflows immediately and is the thing the problem is designed to rule out. - Returning
n / 5only, which undercounts every multiple of 25. - Counting factors of 2 as well and taking the minimum. Correct but redundant: 2s always outnumber 5s.
- Adding
n / 5^kwith a recomputed power each time, which risks overflow in the power for largek. Dividingnin place avoids it.
Full Solution — all languages
class Solution:
def trailingZeroes(self, n):
count = 0
while n > 0:
n //= 5
count += n
return countimport java.util.*;
class Solution {
public int trailingZeroes(int n) {
int count = 0;
while (n > 0) {
n /= 5;
count += n;
}
return count;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int trailingZeroes(int n) {
int count = 0;
while (n > 0) {
n /= 5;
count += n;
}
return count;
}
};/**
* @param {number} n
* @return {number}
*/ var trailingZeroes = function(n) {
let count = 0;
while (n > 0) {
n = Math.floor(n / 5);
count += n;
}
return count;
};