BigInteger 是 Java 提供的一个用于处理任意精度整数的类。它可以用于执行大整数运算,超出了基本数据类型(如 int 或 long)的范围。
下面是一些常用的 BigInteger 方法和操作:
1.创建 BigInteger 对象:
BigInteger bigInt1 = new BigInteger("123456789"); BigInteger bigInt2 = BigInteger.valueOf(987654321);
2.基本运算符和方法:
- 加法:
add(BigInteger val) - 减法:
subtract(BigInteger val) - 乘法:
multiply(BigInteger val) - 除法:
divide(BigInteger val) - 求余:
remainder(BigInteger val) - 求幂:
pow(int exponent) - 绝对值:
abs() - 比较:
compareTo(BigInteger val)
BigInteger sum = bigInt1.add(bigInt2); BigInteger difference = bigInt1.subtract(bigInt2); BigInteger product = bigInt1.multiply(bigInt2); BigInteger quotient = bigInt1.divide(bigInt2); BigInteger remainder = bigInt1.remainder(bigInt2); BigInteger power = bigInt1.pow(2); BigInteger absolute = bigInt1.abs(); int comparison = bigInt1.compareTo(bigInt2);
- 3.转换为其他数据类型:
- 转换为
int:intValue() - 转换为
long:longValue() - 转换为
double:doubleValue() - 转换为字符串:
toString()
int intValue = bigInt1.intValue(); long longValue = bigInt1.longValue(); double doubleValue = bigInt1.doubleValue(); String stringValue = bigInt1.toString();
- 4.其他常用方法:
- 最大公约数:
gcd(BigInteger val) - 位操作:
bitCount(),shiftLeft(int n),shiftRight(int n)
BigInteger gcd = bigInt1.gcd(bigInt2); int bitCount = bigInt1.bitCount(); BigInteger shiftedLeft = bigInt1.shiftLeft(2); BigInteger shiftedRight = bigInt1.shiftRight(3);