标签:
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
分析:题意即为 阶乘尾部的零(求n!中尾部为0的个数)
思路:我们可以对n!进行质因数分解有 n!=2x*3y*5z*...,显然尾部0的个数等于min(x,z),并且我们容易知道min(x,z)==z
因为:阶乘就是1*2*3*...*n
如果我们用[n/k]表示1~n中能被k整除的个数
那么很显然
[n/2] > [n/5] (左边是逢2增1,右边是逢5增1)
[n/2^2] > [n/5^2](左边是逢4增1,右边是逢25增1)
……
[n/2^p] > [n/5^p](左边是逢2^p增1,右边是逢5^p增1)
那么可知n!质因数分解中,2的次幂一定大于5的次幂
于是我们只看n前面有多少个5即可,而n/5就得到了5的个数,还有我们要注意25这种(5和5相乘的结果)
所以还要看n/5里面有多少个5,相当于看n里面有多少个25,还有125,625.。。
代码如下:
class Solution {
public:
int trailingZeroes(int n) {
int count=0;
while(n){
count+=n/5;
n=n/5;
}
return count;
}
};
或者:
class Solution {
public:
int trailingZeroes(int n) {
if (n==0) return 0;
if (n<5 && n>0) return 0;
int count=0;
int i=n/5;
do{
count+=i;
i=i/5;
} while (i>=1);
return count;
}
};
leetcode:Factorial Trailing Zeroes
标签:
原文地址:http://www.cnblogs.com/carsonzhu/p/4677525.html