設計一個算法,計算出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