Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
n! 是1乘到n,其中能构造trailing 0的是2*5 可以
因此找1到n中Min(2的count, 5的count)
所以找1到n中 5 的count
5,10,15,20, 25, 30 ,35, 45......
So is the result simply
n / 5
? Well, not that easy. Notice that some numbers may contribute more than one 5
, like 25 = 5 * 5
. Well, what numbers will contribute more than one 5
? Ok, you may notice that only multiples of the power of 5
will contribute more than one 5
. For example, multiples of 25
will contribute at least two 5
's.
Well, how to count them all? If you try some examples, you may finally get the result, which is
n / 5 + n / 25 + n / 125 + ...
. The idea behind this expression is: all the multiples of 5
will contribute one 5
, the multiples of 25
will contribute one more 5
and the multiples of 125
will contribute another one more 5
... and so on. Now, we can write down the following code, which is pretty short. for(long i = 5; i <= n; i*=5){
c5+= n/i;
}
return c5;
没有评论:
发表评论