LeetCode172. 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!末尾0的个数,最笨的方法莫过于首先计算n!,然后再计算结果末尾的0,这样时明显不符合题目算法时间复杂度要求的。

我们首先看N比较小的一种情况,6!= 1x2x3x4x5x6 = 144 5 = 720 这里面末尾只有一个0,是由5x偶数得到的。同样10!= 6! 7 * 8 9 *10 = 144 5* 7 8 *9 (5 *2) 有两个5,我们可以认为阶乘末尾的0是由于5乘以偶数决定的。而且在阶乘中偶数数量远大于5的个数,那么阶乘末尾的0是有5的个数决定的。所以我们有了下面这段的代码:

    int count_5(int n){
        int result = 0;
        while(n>0 && n%5 == 0){
            result++;
            n = n/5;
        }
        return result;
    }

    int trailingZeroes(int n) {
        int result = 0;
        for(int i=1; i<=n; i++){
            if(i%5 == 0){
                result += count_5(i);
            }
        }
        return result;
    }

count_5计算整数n的可以分解得到多少个5,很可惜这段代码超时了。

继续分析,
n=10的情况下,只有5、10两个元素产生0,
n = 20情况下,有5、10、15、20是个元素产生0
n= 30情况下,有5、10、15、20、25、30六个元素产生0,而且25=5*5 可以产生2个0
同样50、75、100均能产生2个0,
而125= 5*5*5能够产生3个0
这样我们得到
f(n) = sum(n/5, n/25, n/125…)

代码如下:

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

wiki Trailing zero

猜你喜欢

转载自blog.csdn.net/sunao2002002/article/details/52741119