java int biginteger_Java大数字运算之BigInteger

在 Java 中,有许多数字处理的类,比如 Integer 类。但是Integer 类有一定的局限性,下面我们就来看看比 Integer 类更厉害的一个,BigInteger类。

BigInteger类型的数字范围较 Integer 类型的数字范围要大得多。我们都知道 Integer 是 Int 的包装类,int 的最大值为 231-1,如果要计算更大的数字,使用Integer 数据类型就无法实现了,所以 Java 中提供了BigInteger 类来处理更大的数字。 BigInteger 支持任意精度的整数,也就是说在运算中 BigInteger 类型可以准确地表示任何大小的整数值而不会丢失任何信息。

在 BigInteger 类中封装了多种操作!除了基本的加减乘除操作之外,还提供了绝对值、相反数、最大公约数以及判断是否为质数等操作。

使用BigInteger 类,可以实例化一个BigInteger 对象,并自动调用相应的构造函数。BigInteger 类具有很多构造函数,但最直接的一种方式是参数以字符串形式代表要处理的数字。

语法如下:

public BigInteger(String val)

其中,val 是十进制字符串。

如果将 2 转换为 BigInteger 类型,可以使用以下语句进行初始化操作:

BigInteger twoInstance = new BigInteger ("2");

一旦创建了对象实例,就可以调用 BigInteger 类中的一些方法进行运算操作,包括基本的数学运算和位运算以及一些取相反数、取绝对值等操作。下面是 BigInteger 类几种常用的运算方法。

public BigInteger add(BigInteger val):做加法运算

public BigInteger subtract(BigInteger val):做减法运算

public BigInteger multiply(BigInteger val):做乘法运算

public BigInteger divide(BigInteger val):做除法运算

public BigInteger remainder(BigInteger val):做取余操作

public BigInteger pow(int exponet):进行取参数的 exponet 次方操作

public BigInteger negate():取相反数

public BigInteger shiftLegt(int n):将数字左移 n 位,如果 n 为负数,做右移操作

public BigInteger shiftRight(int n):将数字右移 n 位,如果 n 为负数,做左移操作

public int compareTo(BigInteger val):做数字比较操作

public BigInteger max(BigInteger val):返回较大的数值

下面是一个实例。在项目中创建一个类,在类的主方法中创建 BigInteger 类的实例对象,调用该对象的各种方法实现大整数的加减乘除和其他运算,并输出运行结果。

public static void main(String[] args) {

BigInteger bigInstance = new BigInteger("4"); //实例化一个大数字

//取该大数字加2的操作

System.out.println("加法操作:"+

bigInstance.add(new BigInteger("2")));

//取该大数字减2的操作

System.out.println("减法操作:"+

bigInstance.subtract(new BigInteger("2")));

//取该大数字乘以2的操作

System.out.println("乘法操作:"+

bigInstance.multiply(new BigInteger("2")));

//取该大数字除以2的操作

System.out.println("除法操作:"+

bigInstance.divide(new BigInteger("2")));

//取该大数字除以3的商

System.out.println("取商:"+

bigInstance.divideAndRemainder(new BigInteger("3"))[0]);

//取该大数字除以3的余数

System.out.println("取余数:"+

bigInstance.divideAndRemainder(new BigInteger("3"))[1]);

//取该大数字的2次方

System.out.println("做2次方操作:"+

bigInstance.pow(2));

//取该大数字的相反数

System.out.println("取相反数操作:"+

bigInstance.negate());

}

}

以上就是关于 BigInteger 类的详解和实例分析,喜欢的朋友请继续关注脚本之家。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值