Write a program that will calculate the number of trailing zeros
in a factorial of a given number.
N! = 1 * 2 * 3 * 4 … N
zeros(12) = 2 # 1 * 2 * 3 .. 12 = 479001600
that has 2 trailing zeros 4790016(00)
Be careful 1000! has length of 2568 digital numbers.
题目是在求阶乘的末尾0的数目。黑体部分提示我们不能算出结果再算0的个数。事实上,末尾产生一个零阶乘的数就可以分离出一个2*5,阶乘的式子里边分离2的个数比分离5的个数多得多,所以1 * 2 * 3 * 4 … N式中有几个5的倍数,就可以在结尾产生几个零。
public static int zeros(int n){
int a = 0;
for(int i = 0; i < n; i++){
int j = i;
if(j % 5 == 0) {
a++;
j /=5;//检查j可以分离出几个5;
}
}
return a;
}