LeetCodeOJ_172_Factorial Trailing Zeroes

題目:

Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.

分析:

【轉】原地址
結論:對於n的階乘n!,其因式分解中,如果存在一個因子“5”,那麼它必然對應着n!末尾的一個“0”。

證明:
(1)當n < 5時, 結論顯然成立。
(2)當n >= 5時,令n!= [5k * 5(k-1) * … * 10 * 5] * a,其中 n = 5k + r (0 <= r <= 4),a是一個不含因子“5”的整數。
對於序列5k, 5(k-1), …, 10, 5中每一個數5i(1 <= i <= k),都含有因子“5”,並且在區間(5(i-1),5i)(1 <= i <= k)內存在偶數,也就是說,a中存在一個因子“2”與5i相對應。即,這裏的k個因子“5”與n!末尾的k個“0”一一對應。
我們進一步把n!表示爲:n!= 5^k * k! * a(公式1),其中5^k表示5的k次方。很容易利用(1)和迭代法,得出結論1。

令f(x)表示正整數x末尾所含有的“0”的個數, g(x)表示正整數x的因式分解中因子“5”的個數,則:
f(n!) = g(n!) = g(5^k * k! * a) = k + g(k!) = k + f(k!)
所以,最終的計算公式爲:
當0 < n < 5時,f(n!) = 0;
當n >= 5時,f(n!) = k + f(k!), 其中 k = n / 5(取整)。

代碼:

class Solution {
public:
    int trailingZeroes(int n) {
        int result=0;
        int m=n/5;
        if(m==0)
          result=0;
        else
          result=m+trailingZeroes(m);
        return result;
    }
};

結果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章