Given an integer n, return the number of trailing zeroes in n!.
n?
n can be any non-negative integer within a reasonable limit, let’s assume constraints of 0 <= n <= 10^4.100 has two trailing zeroes.To determine the number of trailing zeroes in the factorial of n (denoted as n!), we need to consider the factors that contribute to trailing zeroes. Trailing zeroes are produced by the factor 10, which is the product of 2 and 5. In a factorial, the number of 2s will always be more than or equal to the number of 5s, hence the number of trailing zeroes is determined by the number of times 5 is a factor in the numbers from 1 to n.
To count the number of trailing zeroes, we:
5.25 (this accounts for numbers like 25, 50, etc., which contribute an extra factor of 5).125, 625, and so on.In general, we keep dividing n by 5, 25, 125, etc., summing up the counts until n divided by the increasing powers of 5 is 0.
def trailingZeroes(n: int) -> int:
count = 0
power_of_5 = 5
while n >= power_of_5:
count += n // power_of_5
power_of_5 *= 5
return count
count to 0: This variable will accumulate the number of trailing zeroes.power_of_5 to 5: This is the base factor we start dividing n by.n is greater than or equal to power_of_5:
n // power_of_5 to count.power_of_5 by 5 to consider the next power of 5.count: This gives the total number of trailing zeroes in n!.The time complexity of this solution is O(log_5(n)) because we repeatedly divide n by increasing powers of 5. This is efficient and suitable for the given constraints.
This concludes the solution for counting trailing zeroes in the factorial of an integer n.
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?