Java 大整数类型(BigInteger)
2023-12-28 本文已影响0人
Tinyspot
1. BigInteger
-
java.math.BigInteger
表示任意大小的整数 - BigInteger 内部用一个int[]数组来模拟一个非常大的整数
public class BigInteger extends Number implements Comparable<BigInteger> {
final int[] mag;
}
2. 示例
@Test
public void demo() {
BigInteger bi = new BigInteger("123456789");
System.out.println(bi.pow(5));
BigInteger bi1 = new BigInteger("123456789");
BigInteger bi2 = new BigInteger("12345678987654321");
System.out.println(bi1.add(bi2));
}
3. 类型转换
@Test
public void longValue() {
BigInteger bi = new BigInteger("123456789000");
System.out.println(bi.multiply(bi).longValue());
// BigInteger out of long range
System.out.println(bi.multiply(bi).longValueExact());
}
longValueExact() 如果超出了long型的范围,会抛出ArithmeticException
public long longValueExact() {
if (mag.length <= 2 && bitLength() <= 63)
return longValue();
else
throw new ArithmeticException("BigInteger out of long range");
}