设计一个算法,计算出n阶乘中尾部零的个数
要求:O(logN)的时间复杂度
以n = 101为例
解题思路:
对于n!=1*2…* n,对于相乘最低位能出现0的情况:5*偶数,每一组中偶数的个数多余5的倍数的个数,所以只考虑5x,即每一组中有多少个5x就有多少个零
所以在由1开始,到n结束,5个数为一组:【1,2,3,4,5】,【6,7,8,9,10】,…
能够分为n/5组,分别提取出每组的5x,每组一个(若0!=n mod 5,则,最后的一组可以不去考虑,故只考虑n/5组)
【5,10,…】
记尾数0的个数为sum,目前sum=n/5
对于上述5x的序列,可以写成5【1,2,…,n/5】,此时又可以看成是(n/5)!尾数为0的个数,照上面的做法去分组,
此时sum=sum+n/5/5
以此类推,直到n/5/5/5…/5可分组的个数少于1,即n/5/5…/5=0为止
C++:
class Solution {
public:
/*
* @param n: A long integer
* @return: An integer, denote the number of trailing zeros in n!
*/
long long trailingZeros(long long n) {
// write your code here, try to do it without arithmetic operators.
long num = 0; //注意,此处num一定要用long
while(n!=0)
{
n = n/5;
num+=n;
}
return num;
}
};
Py3:
class Solution:
"""
@param: n: An integer
@return: An integer, denote the number of trailing zeros in n!
"""
def trailingZeros(self, n):
# write your code here, try to do it without arithmetic operators.
num =0
while n//5>0:
n = n//5
num = num+n
return num