不用递归做:
import java.math.BigInteger;
public class Test {
/**
* @param args
* 求出1000的阶乘所有零和尾部零的个数,不用递归做
*/
public static void main(String[] args) {
//所有0
demo1();
//尾部0
demo2();
}
public static void demo2() { //获取1000的阶乘尾部有多少个零
BigInteger bi1 = new BigInteger("1");
for(int i = 1; i <= 1000; i++) {
BigInteger bi2 = new BigInteger(i+"");
bi1 = bi1.multiply(bi2);
}
String str = bi1.toString();
StringBuilder sb = new StringBuilder(str);
str = sb.reverse().toString(); //链式编程
int count = 0;
for(int i = 0; i < str.length(); i++) {
if('0' != str.charAt(i)) {
break;
}else {
count++;
}
}
System.out.println(count);
}
public static void demo1() { //求1000的阶乘中所有的零
BigInteger bi1 = new BigInteger("1");
for(int i = 1; i <= 1000; i++) {
BigInteger bi2 = new BigInteger(i+"");
bi1 = bi1.multiply(bi2);
}
String str = bi1.toString();
int count = 0;
for(int i = 0; i < str.length(); i++) {
if('0' == str.charAt(i)) {
count++;
}
}
System.out.println(count);
}
}
输出:
472
249
用递归做(尾部零的个数):
public class Test {
/**
* @param args
* 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100...1000 1000 / 5 = 200
* 5 * 5 5 * 5 * 2 5 * 5 * 3 5 * 5 * 4 5 * 5 * 5 5 * 5 * 6 200 / 5 = 40
* 5 * 5 * 5 * 1 5 * 5 * 5 * 2 5 * 5 * 5 * 3 5 * 5 * 5 * 4 5 * 5 * 5 * 5 5 * 5 * 5 * 6 5 * 5 * 5 * 7 5 * 5 * 5 * 8
40 / 5 = 8
5 * 5 * 5 * 5 8 / 5 = 1
*/
public static void main(String[] args) {
System.out.println(fun(1000));
}
public static int fun(int num) {
if(num > 0 && num < 5) {
return 0;
}else {
return num / 5 + fun(num / 5);
}
}
}
输出:
249