BigInteger 的常用函数分类说明
一、核心算术运算
方法名 | 功能说明 | 示例(结合代码场景) |
---|---|---|
add(BigInteger val) | 加法运算 | BigInteger sum = a.add(b); |
subtract(BigInteger val) | 减法运算 | BigInteger diff = a.subtract(b); |
multiply(BigInteger val) | 乘法运算 | BigInteger product = a.multiply(b); |
divide(BigInteger val) | 除法运算(取商) | BigInteger quotient = a.divide(b); |
remainder(BigInteger val) | 取余运算 | BigInteger rem = a.remainder(b); |
mod(BigInteger m) | 取模(确保结果非负) | BigInteger mod = a.mod(m); |
pow(int exponent) | 幂运算 | BigInteger power = a.pow(10); |
gcd(BigInteger val) | 最大公约数(GCD) | BigInteger gcd = a.gcd(b); |
二、比较与逻辑判断
方法名 | 功能说明 | 示例(结合代码场景) |
---|---|---|
compareTo(BigInteger val) | 比较大小(返回-1/0/1) | if (a.compareTo(b) > 0) { ... } |
equals(Object x) | 相等性判断 | if (a.equals(BigInteger.ZERO)) { ... } |
isProbablePrime(int certainty) | 质数概率测试 | if (a.isProbablePrime(100)) { ... } |
三、位运算与二进制操作
方法名 | 功能说明 | 示例(结合代码场景) |
---|---|---|
and(BigInteger val) | 按位与 | BigInteger result = a.and(b); |
or(BigInteger val) | 按位或 | BigInteger result = a.or(b); |
xor(BigInteger val) | 按位异或 | BigInteger result = a.xor(b); |
not() | 按位取反 | BigInteger result = a.not(); |
shiftLeft(int n) | 左移 n 位 | BigInteger shifted = a.shiftLeft(3); |
shiftRight(int n) | 右移 n 位(符号扩展) | BigInteger shifted = a.shiftRight(2); |
四、工具与转换方法
方法名 | 功能说明 | 示例(结合代码场景) |
---|---|---|
toString() | 转为十进制字符串 | String s = a.toString(); |
toString(int radix) | 按指定进制转为字符串 | String bin = a.toString(2); |
intValue() | 转为 int (可能溢出) | int num = a.intValue(); |
longValue() | 转为 long (可能溢出) | long num = a.longValue(); |
valueOf(long val) | 静态方法:创建对象 | BigInteger num = BigInteger.valueOf(42); |