源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Java大数字运算之BigInteger <font color="red">原创</font>

  • 时间:2020-07-06 15:11 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Java大数字运算之BigInteger <font color="red">原创</font>
         在 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)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部