Leetcode 172. Factorial Trailing Zeroes
You are given an integer n
, and you need to return the number of trailing zeroes in n!
(n factorial).
100
has two trailing zeroes.10
in the number. Since 10
is the product of 2
and 5
, we need to count the number of 2
s and 5
s in the factors of n!
. Generally, there are more factors of 2
than 5
, so we only need to count the number of times 5
is a factor in the numbers from 1
to n
.k
in the range 1
to n
, count how many times 5
is a factor in k
.floor(n / 5)
to count multiples of 5
floor(n / 25)
to count multiples of 25
(since every 25 contributes an additional factor of 5
)floor(n / 5^i)
until 5^i > n
n
, so its time complexity is O(log n)
.#include <iostream>
class Solution {
public:
int trailingZeroes(int n) {
int count = 0;
while (n >= 5) {
n /= 5;
count += n;
}
return count;
}
};
int main() {
Solution solution;
int n = 100; // Example input
std::cout << "The number of trailing zeroes in " << n << "! is: " << solution.trailingZeroes(n) << std::endl;
return 0;
}
count
to 0.n
by 5
, adding the result to count
.n
is greater than or equal to 5
.count
, which gives the total number of trailing zeroes in n!
.In this solution, we efficiently count the number of factors of 5
in the factorial, leading to the calculation of trailing zeroes.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?