使用BigInteger 可以进行任意位数的数值计算,如下代码分别用递归和循环计算10000的阶乘:
public class Test {
public static void main(String[] args) {
long time1 = System.currentTimeMillis();
System.out.println(time1);
BigInteger count = BigInteger.ONE;
for (int i = 1; i <=10000; i++) {
String str = Integer.toString(i);
BigInteger b1 = new BigInteger(str);
count = count.multiply(b1);
b1 = b1.subtract(BigInteger.ONE);
}
String str = count.toString();
char []ch = str.toCharArray();
for (int i = 0; i < ch.length; i++) {
System.out.print(ch[i]);
if((i+1)%20==0){
System.out.println();
}
}
System.out.println();
long time2 = System.currentTimeMillis();
System.out.println(time2);
System.out.println(time2-time1);
}
}
这是第一种,利用循环计算。
import java.math.BigInteger;
public class Test2 {
public static void main(String[] args) {
long time1 = System.currentTimeMillis();
BigInteger big = sort(new BigInteger("10000"));
String str = big.toString();
char []ch = str.toCharArray();
for (int i = 0; i < ch.length; i++) {
System.out.print(ch[i]);
if((i+1)%20==0){
System.out.println();
}
}
System.out.println();
long time2 = System.currentTimeMillis();
System.out.println(time2-time1);
}
public static BigInteger sort(BigInteger b1){
BigInteger count = BigInteger.ONE;
if(b1.equals(BigInteger.ONE)){
return BigInteger.ONE;
}else{
count = b1.multiply(sort(b1.subtract(BigInteger.ONE)));
return count;
}
}
}
第二种,递归计算。
两种计算方式,所消耗的时间,实际上差不多(通过以上测试可知),但是递归存在栈溢出问题,所以最好使用第一种方法用for循环计算。