BigInteger的初步使用。

使用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循环计算。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值