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
import java.math.BigInteger;

然后可以通过如下两种方式创建实例:

  1. 对于很大的数,传入String类型
1
BigInteger a = new BigInteger("1234567890121312432432543543");
  1. 对于可以用long表示的数:可以直接传入数字类型
1
BigInteger b = new BigInteger(123);

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.math.BigInteger;

public class BigIntegerExample {
public static void main(String[] args) {
BigInteger a = new BigInteger("123456789012345678901234567890");
BigInteger b = new BigInteger("98765432109876543210");

// 加法运算
BigInteger sum = a.add(b);
System.out.println("加法结果: " + sum);

// 乘法运算
BigInteger product = a.multiply(b);
System.out.println("乘法结果: " + product);

// 比较大小
if (a.compareTo(b) > 0) {
System.out.println("a 大于 b");
}

// 幂运算
BigInteger squared = a.pow(2);
System.out.println("a的平方: " + squared);
}
}

Java大数运算之BigInteger
http://blog.ulna520.com/2025/04/01/Java大数运算之BigInger_20250401_204111/
Veröffentlicht am
April 1, 2025
Urheberrechtshinweis