# Moderate 阶层的结尾0个数 @CareerCup

package Moderate;

/**
* Write an algorithm which computes the number of trailing zeros in n
* factorial.
*
* 译文：
*
* 写一个算法计算n的阶乘末尾0的个数。
*
*/
public class S17_3 {

public static int factorsOf5(int i) {
int count = 0;
while (i % 5 == 0) {
count++;
i /= 5;
}
return count;
}

// 第一种方法就是对阶层的所有因子都计算有几个5因子
public static int countFactZeros(int num) {
int count = 0;
for (int i = 2; i <= num; i++) {
count += factorsOf5(i);
}
return count;
}

// 第二种方法，更快地计算出总数
public static int countFactZeros2(int num) {
int count = 0;
if (num < 0) {
System.out.println("Factorial is not defined for negative numbers");
return 0;
}
while(num > 0){
count += num / 5;
num /= 5;
}
return count;
}

public static int factorial(int num) {
if (num == 1) {
return 1;
} else if (num > 1) {
return num * factorial(num - 1);
} else {
return -1; // Error
}
}

public static void main(String[] args) {
for (int i = 1; i < 12; i++) {
System.out.println(i + "! (or " + factorial(i) + ") has " + countFactZeros(i) + " zeros");
System.out.println(i + "! (or " + factorial(i) + ") has " + countFactZeros2(i) + " zeros");
}
}
}


举报原因： 您举报文章：Moderate 阶层的结尾0个数 @CareerCup 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)