題目:Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
解法1::
分析:
對n!做質因數分解n!=2x*3y*5z*...
顯然0的個數等於min(x,z),並且min(x,z)==z
證明:
對於階乘而言,也就是1*2*3*...*n
[n/k]代表1~n中能被k整除的個數
那麼很顯然
[n/2] > [n/5] (左邊是逢2增1,右邊是逢5增1)
[n/2^2] > [n/5^2](左邊是逢4增1,右邊是逢25增1)
……
[n/2^p] > [n/5^p](左邊是逢2^p增1,右邊是逢5^p增1)
隨着冪次p的上升,出現2^p的概率會遠大於出現5^p的概率。
因此左邊的加和一定大於右邊的加和,也就是n!質因數分解中,2的次冪一定大於5的次冪
class Solution {
public:
int trailingZeroes(int n) {
if(n==0) return 0;
int count=0;
while(n>=5){
count+=n/5;
n/=5;
}
return count;
}
};