LEETCODE-Factorial Trailing Zeroes

来源:互联网 发布:网络传真软件破解版 编辑:程序博客网 时间:2024/05/28 11:29

Given an integer n, return the number of trailing zeroes in n!.

Note: Your solution should be in logarithmic time complexity.
利用质因分解,将阶乘进行最终的分解;

对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
……
[n/2^p] > n/5^p
随着幂次p的上升,出现2^p的概率会远大于出现5^p的概率。
因此左边的加和一定大于右边的加和,也就是n!质因数分解中,2的次幂一定大于5的次幂
即:记录n!中有多少个5相乘;

举例: 70
在70!的项中下列这些数中才会整除5(存在5的乘积);
70 65 60 55 50 45 40 35 30 25 20 15 10 5;
分别除以5后得到:(一共有14个5)
14 13 12 11 10 9 8 7 6 5 4 3 2 1;
重复除以5:(一共有2个5)
只有 10 5 可以整除5;
2 1
所以一共有14+2个5;

class Solution {public:    int trailingZeroes(int n) {        int count = 0;        while(n/5 > 0)        {          count = count + n/5;          n /= 5;        }        return count;    }};
0 0