n! = n * (n-1) * (n-2) *... 1;求得到的结果中零的个数
分析:如 10 ! = 1*2*3*4*5*6*7*8*9*10 = (2*5)*10*1*3*4*6*7*8*9
(2*5)*10 的结果中会有零,所以阶乘中零的个数,只需要计算其中这些组合的个数。注意到10 = 2*5,所以归根到底还
是要求计算这个序列中2*5组合的数目。 注意到任意一个偶数都可以拆分成2*n的形式,所以这里只有考虑能拆分得到5的数
的数目即可。
10 = 2*5
15 = 3*5
25 = 5*5 (此时为特殊情况,能拆分成两个5,要细分)
java代码如下
/**
* @author hwy1782@gmail.com
* @creation date 2010-9-23 上午09:29:12
*
* 找出 n! 末尾零的个数
*
*
*/
public class FindZeroNumber {
public static int findNumber(int n){
int numberOfFive = findFiveCount(n);
int result = 0;
result += n /5;
while(numberOfFive > 1){
result += n/(Math.pow(5, numberOfFive));
numberOfFive--;
}
return result;
}
// 若 5^m <= n ,求最大m的值,m = log(n)/log(5)
private static int findFiveCount(int n) {
return (int)(Math.log(n)/Math.log(5));
}
public static void main(String[] args) {
System.out.println(findNumber(1000));
}
}