【LeetCode】172. Factorial Trailing Zeroes


Factorial Trailing Zeroes

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!做質因數分解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) {
        int ret = 0;
        while(n)
        {
            ret += n/5;
            n /= 5;
        }
        return ret;
    }
};


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM