Java大数运算之BigInteger
每日一言
Fight with all your might. With those young kids, give your mind and heart a solid workout. Let your heart, which had dried up and gotten stiff, beat once more. – Yoake Ryou
from ReLIFE
BigInteger
BigInteger 是 java.math 包下的一个类,它提供了一种表示任意大小的整数的方式。理论上它可以表示的整数的大小只受限于你电脑内存的大小。
BigIntger的特性
- 不可变性:这点与String类型非常相似,当一个BigInteger类型创建后其内部表示的数值就不能被改变,所有对
BigeInteger对象进行运算的方法(如加、减、乘、除)都不会修改原始对象,而是会返回一个新的包含运算结果的BigInteger对象。 - 基于对象:
BigInteger是一个类,因此它的实例是对象。 - 方法运算:不能直接使用标准的运算符(
+,-,*,/,%)对BigInteger对象进行运算。必须调用它提供的相应方法。
如何创建BigInteger
首先需要引包:
1 | |
然后可以通过如下两种方式创建实例:
- 对于很大的数,传入String类型
1 | |
- 对于可以用long表示的数:可以直接传入数字类型
1 | |
BigInteger运算
BigInteger类提供了丰富的数学运算方法,以下表格列出了常用的运算方法:
| 运算 | 方法 | 描述 | 示例 |
|---|---|---|---|
| 加法 | add(BigInteger val) |
返回this + val的结果 | a.add(b) |
| 减法 | subtract(BigInteger val) |
返回this - val的结果 | a.subtract(b) |
| 乘法 | multiply(BigInteger val) |
返回this × val的结果 | a.multiply(b) |
| 除法 | divide(BigInteger val) |
返回this ÷ val的商 | a.divide(b) |
| 余数 | remainder(BigInteger val) |
返回this ÷ val的余数 | a.remainder(b) |
| 取模 | mod(BigInteger m) |
返回this模m的结果 | a.mod(b) |
| 除法和余数 | divideAndRemainder(BigInteger val) |
返回包含商和余数的数组 | a.divideAndRemainder(b) |
| 幂运算 | pow(int exponent) |
返回this的exponent次方 | a.pow(3) |
| 比较 | compareTo(BigInteger val) |
比较两个数的大小 | a.compareTo(b) |
| 最大值 | max(BigInteger val) |
返回较大的数 | a.max(b) |
| 最小值 | min(BigInteger val) |
返回较小的数 | a.min(b) |
| 绝对值 | abs() |
返回绝对值 | a.abs() |
| 相反数 | negate() |
返回相反数 | a.negate() |
| 符号值 | signum() |
返回符号值(1, 0, -1) | a.signum() |
| 位移 | shiftLeft(int n), shiftRight(int n) |
返回左/右移n位的结果 | a.shiftLeft(2) |
| 与运算 | and(BigInteger val) |
返回按位与的结果 | a.and(b) |
| 或运算 | or(BigInteger val) |
返回按位或的结果 | a.or(b) |
| 异或运算 | xor(BigInteger val) |
返回按位异或的结果 | a.xor(b) |
| 取反 | not() |
返回按位取反的结果 | a.not() |
使用示例
1 | |
Java大数运算之BigInteger
http://blog.ulna520.com/2025/04/01/Java大数运算之BigInger_20250401_204111/