文章目录
BigInteger
和 BigDecimal
是 Java 中用于高精度数学计算的类,位于 java.math
包中。
1. BigInteger 基本使用
BigInteger
适用于任意精度的整数运算,支持大数计算,如超出 long
范围的数。
1.1 创建 BigInteger
import java.math.BigInteger;
public class BigIntegerDemo {
public static void main(String[] args) {
// 通过字符串创建
BigInteger bigInt1 = new BigInteger("123456789012345678901234567890");
// 通过数值创建(valueOf 仅适用于 long 类型)
BigInteger bigInt2 = BigInteger.valueOf(9876543210L);
System.out.println("bigInt1: " + bigInt1);
System.out.println("bigInt2: " + bigInt2);
}
}
1.2 常见运算
1.2.1 加法
public class BigIntegerOperations {
public static void main(String[] args) {
BigInteger a = new BigInteger("12345678901234567890");
BigInteger b = new BigInteger("98765432109876543210");
// 加法
BigInteger sum = a.add(b);
System.out.println("加法: " + sum);
1.2.2 减法
// 减法
BigInteger diff = a.subtract(b);
System.out.println("减法: " + diff);
1.2.3 乘法
// 乘法
BigInteger product = a.multiply(b);
System.out.println("乘法: " + product);
1.2.4 除法
// 除法
BigInteger quotient = a.divide(b)