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

来源:互联网 发布:北京软件游戏编程培训 编辑:程序博客网 时间:2024/05/17 01:49

问题描述:

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 nint 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
原创粉丝点击