BigInteger怎么用
时间: 2023-11-20 10:05:37 浏览: 64
BigInteger是Java中的一个类,用于处理大整数问题,可以用于任意精度的整数运算。下面是一些基本的使用方法:
1. 创建一个BigInteger对象:
```
BigInteger bigInt = new BigInteger("123456789");
```
2. 进行基本的算术运算:
```
BigInteger a = BigInteger.valueOf(10);
BigInteger b = BigInteger.valueOf(20);
BigInteger c = a.add(b); // c = a + b
BigInteger d = b.subtract(a); // d = b - a
BigInteger e = a.multiply(b); // e = a * b
BigInteger f = b.divide(a); // f = b / a
BigInteger g = b.mod(a); // g = b % a
```
3. 进行比较运算:
```
BigInteger a = BigInteger.valueOf(10);
BigInteger b = BigInteger.valueOf(20);
if (a.compareTo(b) < 0) {
System.out.println("a is less than b");
} else if (a.compareTo(b) > 0) {
System.out.println("a is greater than b");
} else {
System.out.println("a equals b");
}
```
4. 转换为其他数据类型:
```
BigInteger a = BigInteger.valueOf(123456789);
int b = a.intValue(); // b = 123456789
long c = a.longValue(); // c = 123456789
float d = a.floatValue(); // d = 1.23456792E8
double e = a.doubleValue(); // e = 1.23456789E8
```
5. 其他常用方法:
```
BigInteger a = BigInteger.valueOf(10);
BigInteger b = BigInteger.valueOf(20);
BigInteger c = BigInteger.valueOf(30);
BigInteger max = a.max(b); // max = b
BigInteger min = a.min(b); // min = a
BigInteger gcd = b.gcd(c); // gcd = 10
boolean isProbablePrime = a.isProbablePrime(10); // false
```
阅读全文