您的位置:首页 > 大数据 > 人工智能

leetcode[172]:Factorial Trailing Zeroes

2015-06-25 21:25 411 查看
Factorial Trailing Zeroes

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

Note: Your solution should be in logarithmic time complexity.

int trailingZeroes(int n) {
int count=0;
int k;
while(n>0)
{
k=n/5;
count+=k;
n=k;
}
return count;
}


计算小于等于n的数字中5的个数即可。

因为5的个数比2少,所以2和5组成的pair的个数由5的个数决定。

观察15! = 有3个5(来自其中的5, 10, 15), 所以计算n/5就可以。

但是25! = 有6个5(有5个5来自其中的5, 10, 15, 20, 25, 另外还有1个5来自25=(5*5)的另外一个5),

所以除了计算n/5, 还要计算n/5/5, n/5/5/5, n/5/5/5/5, …, n/5/5/5,,,/5直到商为0。

参考: http://blog.csdn.net/feliciafay/article/details/42336835
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  math