题目
编程求解 N! 所得数末尾有多少个 0 ?( n 由键盘输入,1000 < N < 10000)
分析
假设末尾 0 的个数为 K,很容易想到的:
在规定的数据范围内,直接求解 所得结果会很大,必然会有数据溢出的情况,所以,不能直接求解。
那么,换思路, 可以写成:
对其中的合数再进行质因数分解, 又可以写成质数的乘积:
末尾 K 个 0 就是:
结合上面两个公式,可以推导出:
所以:
再进一步,可以断定 中
是一定成立的,所以最后可得:
分析到这里,解题思路就可以转化为:遍历 1 ~ N 分解质因数,得到数字 5 的个数就是 K 值。
算法代码
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int count = 0, temp;
for (int i = 1; i <= n; i++) {
temp = i;
while (temp % 5 == 0) {
count += 1;
temp /= 5;
}
}
System.out.println(count);
}
}