BigInteger
在Java中,整数类型有四种类型:byte(一个字节)、short(2个字节)、int(四个字节)、long(8个字节)
超出取值范围上面类型无法使用,这时就需要用BigInteger,他有范围但十分巨大
常用方法
1、public BigInteger(int num,Random rnd) //获取随机大整数,范围:[0~2的num次方-1]
2、public BigInteger(String val) //获取指定的大整数,字符串必须是整数
3、public BigInteger(String val,int radix) //获取指定进制的大整数,字符串必须是整数
4、public static BigInteger valueOf(long val) //静态方法获取BigInteger的对象,内部有优化
4与2相比:4只能在long数据范围内
4在内部对常用的数字-16~16进行了优化,如果多次获取不会重新创建新的
4对象创建了内部数据不会改变
import java.math.BigInteger;
import java.util.Random;
public class Main {
public static void main(String[] args) throws CloneNotSupportedException{
//1、public BigInteger(int num,Random rnd) //获取随机大整数,范围:[0~2的num次方-1]
for(int i=0;i<10;i++){
BigInteger b1=new BigInteger(3,new Random());
System.out.print(b1+" ");
}
// 2、public BigInteger(String val)//获取指定的大整数,字符串必须是整数
BigInteger b2=new BigInteger("99999999");
System.out.println(b2);
//3、public BigInteger(String val,int radix)//获取指定进制的大整数,字符串必须是整数
BigInteger b3=new BigInteger("99999",16);
System.out.println(b3);
//4、public static BigInteger valueOf(long val)//静态方法获取BigInteger的对象,内部有优化
// 4与2相比:4只能在long数据范围内
//4在内部对常用的数字-16~16进行了优化,如果多次获取不会重新创建新的
BigInteger b6=BigInteger.valueOf(11);
BigInteger b7=BigInteger.valueOf(11);
System.out.println(b6==b7);//true
BigInteger b4=BigInteger.valueOf(99999);
BigInteger b5=BigInteger.valueOf(99999);
System.out.println(b5==b4);//false
//4对象创建了内部数据不会改变
BigInteger result=b6.add(b7);
System.out.println(b6==result);//false
System.out.println(b7==result);//false
}
}
BigInteger常见成员方法
public BigInteger add(BigInteger val)//加法
public BigInteger subtract(BigInteger val)//减法
public BigInteger multiply(BigInteger val)//乘法
public BigInteger divide(BigInteger val)//除法,获取商
public BigInteger[] divideAndRemainder(BigInteger val)//除法,获取商和余数
public boolean equals(Object x)//比较是否相同
public BigInteger pow(int exponent)//次幂
public BigInteger max/min(BigInteger val)//返回较大者/较小值
public int intValue(BigInteger val)//转为int类型整数,超出范围数据有误
都用对象.方法名(参数)即可,divideAndRemainder需要用数组接收