Given an integer n
, return the number of trailing zeroes in n!
.
Note that n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1
.
For example:
n = 3
, then the output should be 0
because 3! = 6
which has no trailing zeroes.n = 5
, then the output should be 1
because 5! = 120
which has one trailing zero.n = 10
, then the output should be 2
because 10! = 3628800
which has two trailing zeroes.What is the most efficient way to calculate the number of trailing zeroes without actually calculating the factorial? Can you write code with logarithmic time complexity?
This problem asks us to find the number of trailing zeroes in the factorial of a given number n
. A naive approach would be to calculate the factorial and then count the trailing zeroes. However, this is not efficient and can lead to overflow issues for larger values of n
.
The key idea is that trailing zeroes are produced by factors of 5 and 2. Since there are always more factors of 2 than 5, we only need to count the number of factors of 5 in the prime factorization of n!
.
To count the number of factors of 5, we can use the following approach:
n
by 5 and add the quotient to the count.n
by 25 (5^2) and add the quotient to the count.n
by 125 (5^3) and add the quotient to the count.Here's the code implementation in Java:
class Solution {
/**
* Given an integer n, return the number of trailing zeroes in n!.
*
* Note that n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1.
*
* @param n the integer
* @return the number of trailing zeroes in n!
*/
public int trailingZeroes(int n) {
int count = 0;
while (n > 0) {
n /= 5;
count += n;
}
return count;
}
}
Here's the code implementation in Python:
class Solution:
def trailingZeroes(self, n: int) -> int:
count = 0
while n > 0:
n //= 5
count += n
return count
The time complexity of this solution is O(log5n) because we are dividing n
by powers of 5 in each iteration. The number of iterations is logarithmic with base 5.
The space complexity of this solution is O(1) because we are only using a constant amount of extra space.
n
is 0, the number of trailing zeroes is 0.n
is a large number, the number of trailing zeroes can be large, but the algorithm will still work correctly.Here are a few examples:
n = 3
: The number of trailing zeroes is 0.n = 5
: The number of trailing zeroes is 1.n = 10
: The number of trailing zeroes is 2.n = 25
: The number of trailing zeroes is 6 (5 from 5, 10, 15, 20 and 1 from 25 which has two 5s).