Factorial Trailing Zeroes(OJ) 求其阶乘尾数0的个数[1808548329]

问题描述:

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

Note: Your solution should be in logarithmic time complexity.

问题分析:

一个2和一个5相乘就会产生一个0,阶乘过程中5的个数肯定会比2多

例如: 5! =(2 * 2 * 2 * 3 * 5). 所以 0个数 is 1.

          11! (2 8 * 34 * 52 * 7). 所以 0个数 is 2.

问题转化为求阶乘过程中5的个数,而且注意25里有2个5,125有三个五,所以问题变为:

count= floor(n/5) + floor(n/25) + floor(n/125) + ....

网上有一个经典写法:

// Function to return trailing 0s in factorial of n
int findTrailingZeros(int  n)
{
    // Initialize result
    int count = 0;
 
    // Keep dividing n by powers of 5 and update count
    for (int i=5; n/i>=1; i *= 5)
          count += n/i;
 
    return count;
}
在oj上提交会发现n = 1808548329时WA了

原因就是 i*5一直连乘时出现i = 14时,内存溢出(5^13 = 1220703125 < 2^31, but 5^14 = 6103515625 > 2^32)

但是 6103515625 % 2^32 = 1808548329 < 2 ^31,即1808548329 为合理输入

解决办法:

int trailingZeroes(int n) {
        
        int count = 0;
        for(int i = 5; n/i >= 1;)
        {
            count += n/i;
            n /= 5;
        }
        
        return count;
    }



---附加-----
2015年加油!注意细节,关注思想。

一直都断断续续,但是依然继续,我依然很菜,但是我依然坚持成长。


Trust in the Load with all your heart and learn not on your own understanding;

in all your ways acknowledge him, and he will make your paths straight.  -[Proverbs 3:5-6]





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值