class Solution:
def trailingZeroes(self, n: int) -> int:
count = 0
while n > 0:
n //= 5
count += n
return count
class Solution {
public:
int trailingZeroes(int n) {
int count = 0;
while (n > 0) {
n /= 5;
count += n;
}
return count;
}
};
class Solution {
public int trailingZeroes(int n) {
int count = 0;
while (n > 0) {
n /= 5;
count += n;
}
return count;
}
}
var trailingZeroes = function(n) {
let count = 0;
while (n > 0) {
n = Math.floor(n / 5);
count += n;
}
return count;
};
The "Factorial Trailing Zeroes" problem asks: Given an integer n
, return the number of trailing zeroes in n!
(that is, the factorial of n
).
Constraints:
n
(0 ≤ n ≤ 104 or higher).n!
.
At first glance, you might think to compute the factorial of n
and count the number of zeroes at the end. However, factorials grow extremely quickly, and even for moderate values of n
, the result will not fit in standard data types. Therefore, a brute-force approach of calculating n!
directly is not feasible.
Next, think about what causes trailing zeroes in a number: each trailing zero comes from a factor of 10, which is the product of 2 and 5. In factorials, there are usually more factors of 2 than 5, so the number of trailing zeroes is determined by the number of times 5 appears as a factor in the numbers from 1 to n
.
The key insight is to count how many times 5 is a factor in all numbers from 1 to n
. This is much more efficient than calculating the factorial itself.
To count the number of trailing zeroes in n!
, follow these steps:
n
is greater than zero:
n
by 5 (integer division) and add the result to the counter.n
to n // 5
.n
becomes zero.n
, including all higher powers of 5.
Let's take n = 30
as an example.
Step 1: Count how many multiples of 5 are ≤ 30.
Brute-force approach:
n
due to exponential growth.n
by 5 each time, so it runs O(log5 n) times.
The key insight to solving the "Factorial Trailing Zeroes" problem is understanding that trailing zeroes are formed from pairs of factors 2 and 5, and that factors of 2 are always more abundant than factors of 5 in a factorial. By counting the total number of times 5 appears in the prime factorization of all numbers from 1 to n
, including higher powers, we can efficiently determine the number of trailing zeroes in n!
without ever computing the factorial itself. This makes the solution both elegant and highly efficient.