If we just count the zeros we can see that it follows to be 0,0,0,0,0,1,1,1,1,1,2,2,2,2,2 .... and so fourth. That alone can be modeled with a linear function, f(x) = floor(x/5)
However, there is one additional thing. Notice how there is a jump of an additional zero on 25!. It will follow that every 5^n there will be another one of this jumps, and they add on to the previous, we can fix our model now to be f(x) = floor(x/5) + floor(x/25)
But to get this right, we will need to add floor(x/pow(5,n) dependently on just how large n actually gets.
f(x) = floor(x/5) + floor(x/25) + floor(x/125) + ....+ floor(x/pow(5, n)) is the true solution.
Complexity: Because our power number will expand exponentially, we will reach our target in logarithmic time, and so there will only be a logarithmic amount of summations. O(logn) time and space, but O(1) space iterative
import math
class Solution:
def trailingZeroes(self, n):
"""
:type n: int
:rtype: int
"""
if n <= 4:
return 0
elif n <= 9:
return 1
return math.floor(n / 5) + self.trailingZeroes(math.floor(n / 5))
import math
class Solution:
def trailingZeroes(self, n):
"""
:type n: int
:rtype: int
"""
five_pow = 1
current_power = math.pow(5, five_pow)
total_zeros = 0
while current_power <= n:
total_zeros += math.floor(n/current_power)
five_pow += 1
current_power = math.pow(5, five_pow)
return total_zeros