当我们想求100的阶乘的时候,long类型也会出现溢出,我们可以用到java.math包下的BigInteger类来实现高精度运算。可以认为一个BigInteger对象就是一个数。
主要是对高精度的数进行加减乘除余。
一、构造方法
主要用到的是传入字符串创建BigInteger对象
- BigInteger a = new BigInteger(String num); //通过num创建对象
- BigInteger b = new BigInteger(String num,int n)通过num的n进制数创建对象
二、常用方法
1、加法 add()
用到的是该类的add方法,传入一个BigInteger对象,返回也是一个BigInteger对象
代码示例:
import java.math.BigInteger;
public class Test {
public static void main(String[] args) {
BigInteger a = new BigInteger("9999999999999999999");
BigInteger b = new BigInteger("9999999999999999999");
System.out.println(a.add(b)); //输出19999999999999999998
}
}
2、减法subtract()
代码示例:
import java.math.BigInteger;
public class Test {
public static void main(String[] args) {
BigInteger a = new BigInteger("999999999999999999999999999999999");
BigInteger b = new BigInteger("9999999999999999999");
System.out.println(a.subtract(b)); //输出1000000000000009999999999999999998
}
}
3、乘法 multiply()
代码示例:
import java.math.BigInteger;
public class Test {
public static void main(String[] args) {
BigInteger a = new BigInteger("99999999");
BigInteger b = new BigInteger("99999999");
System.out.println(a.multiply(b)); //输出9999999800000001
}
}
4、除法 divide()
mod()方法取模 。永远为正
remainder()方法取余。可能会出现负数。
public class Test {
public static void main(String[] args) {
BigInteger a = new BigInteger("4");
BigInteger b = new BigInteger("2");
System.out.println("输出为:"+a.divide(b)); //输出2
System.out.println("余数为:"+a.remainder(b)); // 输出0
}
}
5、求最大公约数gcd()
代码示例:
import java.math.BigInteger;
public class Test {
public static void main(String[] args) {
BigInteger a = new BigInteger("48");
BigInteger b = new BigInteger("8");
System.out.println(a.gcd(b)); //输出8
}
}
6、转换成任意进制的字符串
使用的方法是toString(int n); 传入的n为要转换的n进制
代码示例:
import java.math.BigInteger;
public class Test {
public static void main(String[] args) {
BigInteger a = new BigInteger("8");
System.out.println(a.toString(2)); //输出1000
}
}
三、缺点
BigInteger类每一次创建对象太消耗时间,可能编译超时,最好不要循环创建对象。高精度的话也只爆long的时候在用。