java如何使用大数
使用 BigInteger 类处理大整数
Java 中的 BigInteger 类位于 java.math 包中,用于处理任意精度的整数。创建 BigInteger 对象可以通过字符串或字节数组:
import java.math.BigInteger;
BigInteger bigInt1 = new BigInteger("12345678901234567890");
BigInteger bigInt2 = BigInteger.valueOf(987654321L);
常用算术运算方法包括:
add(BigInteger val):加法subtract(BigInteger val):减法multiply(BigInteger val):乘法divide(BigInteger val):除法mod(BigInteger val):取模
BigInteger sum = bigInt1.add(bigInt2);
BigInteger product = bigInt1.multiply(bigInt2);
使用 BigDecimal 类处理高精度小数
BigDecimal 类用于高精度的浮点数运算,同样位于 java.math 包。创建方式类似:

import java.math.BigDecimal;
BigDecimal decimal1 = new BigDecimal("123.456789");
BigDecimal decimal2 = BigDecimal.valueOf(789.123456);
算术运算方法与 BigInteger 类似,但需要注意精度控制:
setScale(int newScale, RoundingMode mode):设置小数位数和舍入模式
BigDecimal sum = decimal1.add(decimal2);
BigDecimal divided = decimal1.divide(decimal2, 10, RoundingMode.HALF_UP);
大数比较和转换
比较两个大数使用 compareTo 方法:

int comparison = bigInt1.compareTo(bigInt2); // 返回 -1, 0, 或 1
转换为基本类型需注意范围限制:
long val = bigInt1.longValue(); // 可能丢失精度
String str = bigInt1.toString(); // 安全转换
大数运算的注意事项
使用大数类时需注意性能开销,因其运算速度远慢于基本类型。对于幂运算等复杂操作:
BigInteger power = bigInt1.pow(100); // 计算100次幂
BigInteger gcd = bigInt1.gcd(bigInt2); // 最大公约数
对于密码学等场景,可使用 probablePrime 方法生成大素数:
BigInteger prime = BigInteger.probablePrime(256, new Random());






