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的次冪

 

解法一:

從1到n中提取所有的5

複製代碼
class Solution {
public:
    int trailingZeroes(int n) {
        int ret = 0;
        for(int i = 1; i <= n; i ++)
        {
            int tmp = i;
            while(tmp%5 == 0)
            {
                ret ++;
                tmp /= 5;
            }
        }
        return ret;
    }
};
複製代碼

 

解法二:

由上述分析可以看出,起作用的只有被5整除的那些數。能不能只對這些數進行計數呢?

存在這樣的規律:[n/k]代表1~n中能被k整除的個數。

因此解法一可以轉化爲解法二

複製代碼
class Solution {
public:
    int trailingZeroes(int n) {
        int ret = 0;
        while(n)
        {
            ret += n/5;
            n /= 5;
        }
        return ret;
    }
};
發佈了27 篇原創文章 · 獲贊 4 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章