<LeetCode OJ> 172. Factorial Trailing Zeroes

172. Factorial Trailing Zeroes

My Submissions
Total Accepted: 45801  Total Submissions: 147715  Difficulty: Easy

Given an integer n, return the number of trailing zeroes in n!.

Note: Your solution should be in logarithmic time complexity.



分析:

缩小问题规模找规律:1!=1,2!=2,3!=6,4!=24,5!=120,6!=720,7!=5040,8!=40320,9!=362880,10!=3628800
草,知道和5,10有关,但是没做对,看了下别人家的思路:
核心思想每一个尾巴上的0,绝对是2和5的结果
绝对规律1:2的个数绝对比5的个数多(这很显然)
绝对规律2:有多少个质因子5就有多少个尾巴0
26!有多少个质因子5?5,10,15,20,25(有的数贡献两个5,6个)
51!有多少个质因子5?5,10,15,20,25,30,35,40,45,50,(12个),最终规律:5的个数,n/5+n/25+n/125

class Solution {
public:
    int trailingZeroes(int n) {
        if(n<5)
            return 0;
        int cnt = 0;   //求质因子5的个数
           
        while(n/5 != 0) {    
            n /= 5;   
            cnt += n;   
        }   
           
        return cnt;   
    }
};


来源于别人家的具体分析:

Well, to compute the number of trailing zeros, we need to first think clear about what will generate a trailing 0? Obviously, a number multiplied by 10 will have a trailing 0 added to it. So we only need to find out how many 10's will appear in the expression of the factorial. Since10 = 2 * 5 and there are a bunch more 2's (each even number will contribute at least one 2), we only need to count the number of 5's.

Now let's see what numbers will contribute a 5. Well, simply the multiples of 5, like 5, 10, 15, 20, 25, 35, .... So is the result simply n / 5? Well, not that easy. Notice that some numbers may contribute more than one 5, like 25 = 5 * 5. Well, what numbers will contribute more than one 5? Ok, you may notice that only multiples of the power of 5 will contribute more than one5. For example, multiples of 25 will contribute at least two 5's.

Well, how to count them all? If you try some examples, you may finally get the result, which is n / 5 + n / 25 + n / 125 + .... The idea behind this expression is: all the multiples of 5 will contribute one 5, the multiples of 25 will contribute one more 5 and the multiples of 125 will contribute another one more 5... and so on. Now, we can write down the following code, which is pretty short.


注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/50443069

原作者博客:http://blog.csdn.net/ebowtang

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值