math and geometry December 1, 2022

Factorial trailing zeroes

Time O(log(n)) Space O(1) Open original problem

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)