public class Solution {
    public int TrailingZeroes(int n) {
        if (n == 0)
            {
                return 0;
            }
            else
            {
                var x = n / 5;
                var y = TrailingZeroes(x);
                return x + y;
            }
    }
}

https://leetcode.com/problems/factorial-trailing-zeroes/#/description

 

此类问题很显然属于数学问题,一定要找到其中的本质规律才能得到正确的数学模型。
两个大数字相乘,都可以拆分成多个质数相乘,而质数相乘结果尾数为0的,只可能是2*5。如果想到了这一点,那么就可以进一步想到:两个数相乘尾数0的个数其实就是依赖于2和5因子的个数。又因为每两个连续数字就会有一个因子2,个数非常充足,所以此时只需要关心5因子的个数就行了。
对于一个正整数n来说,怎么计算n!中5因子的个数呢?我们可以把5的倍数都挑出来,即:
令n! = (5*K) * (5*(K-1)) * (5*(K-2)) * ... * 5 * A,其中A就是不含5因子的数相乘结果,n = 5*K + r(0<= r <= 4)。假设f(n!)是计算阶乘n!尾数0的个数,而g(n!)是计算n!中5因子的个数,那么就会有如下公式:
f(n!) = g(n!) = g(5^K * K! * A) = K + g(K!) = K + f(K!),其中K=n / 5(取整数)。
很显然,当0 <= n <= 4时,f(n!)=0。结合这两个公式,就搞定了这个问题了。举几个例子来说:

f(5!) = 1 + f(1!) = 1
f(10!) = 2 + f(2!) = 2
f(20!) = 4 + f(4!) = 4
f(100!) = 20 + f(20!) = 20 + 4 + f(4!) = 24
f(1000!) = 200 + f(200!) = 200 + 40 + f(40!) = 240 + 8 + f(8!) = 248 + 1 + f(1) =249

以上解释参考地址:https://www.cnblogs.com/kuliuheng/p/4102917.html

python的实现:

1 class Solution:
2     def trailingZeroes(self, n: int) -> int:
3         count = 0
4         while (n > 0):
5             count += n // 5
6             n = n // 5
7         return count

 

Java版:

 1 class Solution {
 2     public int trailingZeroes(int n) {
 3         int count = 0;
 4         while(n != 0){
 5             count += n / 5;
 6             n = n / 5;
 7         }
 8         return count;
 9     }
10 }

 

posted on 2017-04-22 10:45  Sempron2800+  阅读(92)  评论(0编辑  收藏  举报