Factorial trailing zeroes

December 1, 2022

math-and-geometry

Problem URL: Factorial trailing zeroes

We will count the number of trailing zeroes in the factorial of the given number. We will count the number of 5s in the factorial of the given number. We will keep dividing the number by 5 and add the quotient to the count. At the end we will return the count.

class Solution:
    def trailingZeroes(self, n: int) -> int:
        count = 0
        while n:
            n //= 5
            count += n
        return count

Time complexity: O(log(n))
Space complexity: O(1)