算法:动态规划,f(i) = f(i-1) + f(i!)f(i!)如何计算:每一个可以包含因子5的数都贡献零,贡献的个数就是包含因子5的个数1.找到第一个是5的倍数
2.逐个减5往后遍历,遍历的过程中不断除5来统计末尾连续零的个数 import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
System.out.println(zerosOfTail(n));
}
public static int zerosOfTail(int n) {
if (n < 5) {
return 0;
}
int[] dp = new int[n+1]; // 初始化默认为0,所以dp[1]-dp[4]已经为0了
for (int i = 5; i <= n; i++) {
dp[i] = dp[i-1] + zerosOfFactorial(i);
}
return dp[n];
}
public static int zerosOfFactorial(int n) {
if (n < 5) {
return 0;
}
int result = 0;
int i = 0;
for (i = n; i >= 5; i--) {
if (i % 5 == 0) {
break;
}
}
for (; i >= 5; i -= 5) {
int temp = i;
while (temp % 5 == 0) {
result++;
temp /= 5;
}
}
return result;
}
}