[LeetCode]--172. Factorial Trailing Zeroes

    xiaoxiao2026-05-04  10

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

    Note: Your solution should be in logarithmic time complexity.

    Credits: Special thanks to @ts for adding this problem and creating all test cases.

    实在话这个题看似简单其实挺难。我尝试了先求出n!首先会超出int范围,其次如果是double会用科学计数法。并不能精确到那一位,所以只能换个思路了。就是怎么才能在后面产生0。那肯定就是乘以了10。所以就想到分解因子,最小一对(2,5)肯定会产生10。

    对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的次幂。

    所以我们统计阶乘中有多少个五参与计算即可。

    public int trailingZeroes1(int n) { if (n < 1) return 0; int total = 0; while (n / 5 != 0) { n = n / 5; total += n; } return total; } 相关资源:python入门教程(PDF版)
    最新回复(0)