172 Factorial Trailing Zeroes
Given an integern, return the number of trailing zeroes inn!.
Note:Your solution should be in logarithmic time complexity.
The Idea: First lets take a look at the factorial sequence and see if we can notice a pattern.
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
Recursive
Iterative
Last updated