BigInteger

 

 

package com.mao.one;

import java.math.BigInteger;
import java.util.Random;

public class BigintegerDemo01 {
    public static void main(String[] args) {
        //1.获取一个随机的大整数
        BigInteger bd1 = new BigInteger(4,new Random());
        System.out.println(bd1);//0 ~2^4-1

        //2.获取一个指定的大整数  必须是整数
        BigInteger bd2 = new BigInteger("100");
        System.out.println(bd2);

        //3.获取指定进制的大整数
        //1.字符串中的数字必须是整数
        //2.字符串中的数字必须跟进制吻合 比如二进制中,只能写0和1
        BigInteger bd3 = new BigInteger("100",10);
        BigInteger bd4 = new BigInteger("100",2);
        System.out.println(bd3);
        System.out.println(bd4);

        //4.静态方法获取BigInteger的对象,内部优化
        //1.表示范围小,在long的取值范围之内,如果超出long就不好使
        //2.在内部对常用的数字:-16~ 16 进行了优化
        //提前把-16 ~16 先建好了biginteger的对象,如果多次获取   不会重新创建新的
        BigInteger bd5 = BigInteger.valueOf(16);
        BigInteger bd6 = BigInteger.valueOf(16);
        System.out.println(bd5==bd6);

        BigInteger bd7 = BigInteger.valueOf(17);
        BigInteger bd8 = BigInteger.valueOf(17);
        System.out.println(bd7==bd8);

        //5.对象一旦创建 内部数据不会发生改变
        BigInteger bd9 = BigInteger.valueOf(1);
        BigInteger bd10 = BigInteger.valueOf(2);
        BigInteger resul = bd9.add(bd10);
        System.out.println(resul);
        //此时不会修改参与计算BigInteger对象中的值,而是产生了一个新的BigInteger对象记录3
    }
}

 

 

 

 

 

package com.mao.one;

import java.math.BigInteger;

public class BigintegerDemo02 {
    public static void main(String[] args) {
        //1.创建两个BigInteger对象
        BigInteger bd1 = BigInteger.valueOf(10);
        BigInteger bd2 = BigInteger.valueOf(5);

        //2.加法
        BigInteger bd3 = bd1.add(bd2);
        System.out.println(bd3);

        //3.除法,获取商和余数
        BigInteger[] arr = bd1.divideAndRemainder(bd2);
        System.out.println(arr.length);
        System.out.println(arr[0]);//
        System.out.println(arr[1]);//余数

        //4.比较是否a相同
        boolean resul = bd1.equals(bd2);
        System.out.println(resul);

        //5.次幂
        BigInteger pow = bd1.pow(2);
        System.out.println(pow);

        //6.max
        BigInteger max = bd1.max(bd2);
        System.out.println(max);

        //7.转为int类型整数,超出范围数据有误
        BigInteger bd6 = BigInteger.valueOf(1000);
        int i = bd6.intValue();
        System.out.println(i);

        BigInteger bd7 = BigInteger.valueOf(999L);
        long j = bd7.longValue();
        System.out.println(j);


    }
}

 

posted @ 2022-08-17 15:11  是貓阿啊  阅读(31)  评论(0)    收藏  举报