大数字运算
在Java中提供了大数字的操作类,即java.math.BigInteger类与java.math.BigDecimal类。
BigInteger类型的数字范围比较Integer类型的数字范围要大的多,BigInteger支持任意精度的整数,也就是说,在运算中BigInteger类型可以准确的表示任何大小的整数值而不会丢失信息。在BigInteger类型中封装了多种操作,处理最简单的加减乘除,还提供了绝对值,相反数,最大公约数,以及判断是否为质数的等操作。
使用BigInteger类,可以实例化一个BigInteger对象,并且自动调用相应的构造函数,BigInteger类具有很多的构造函数,但是最直接的一种方式是参数以字符串的形式代表要处理的数字,语法如下:
public BigInteger(String val)
//val是十进制字符串
如果将十字“r”转换为BigInteger类型,使用的语法是:
BigInteger RInstance=new BigInteger("2");
一旦创建了对象实例,就可以调用BigInteger类中的一些方法进行运算操作,包括最基本的数字运算和位运算以及一些相反数,取绝对值等操作。
【1】public BigInteger add (BigInteger val);做加法运算
【2】public BigInteger subtract (BigInteger val);做减法运算
【3】public BigInteger multiply(BigInteger val);做乘法运算
【4】public BigInteger divide(BigInteger val);做除法运算
【5】public BigInteger remainder(BigInteger val);做取余操作
【6】public BigInteger[] divideAndRemainder(BigInteger val);用数组返回余数和商,结果数组中的第一个值为商,第二个值为余数
【7】public BigInteger pow(int exponent);进行取参数的exponent次方操作
【8】public BigInteger negate();取相反数
【9】public BigInteger shiftLeft(int n);将数字向左移动n位,如果n 位负数则向右移动
【10】public BigInteger shiftRight(int n);将数字向右移动n位,如果你为负数,则向左移动
【11】public BigInteger and (BigInteger val);做与操作
【12】public BigInteger or (BigInteger val);做或操做
【13】public int compareTo (BigInteger val);做数字比较操作
【14】public boolean equals(Object x);当参数x是BigInteger类型的数字并且数值相等返回true
【15】public BigInteger min(BigInteger val);返回较小的数
【16】public BigInteger max(BigInteger val);返回较大的数
在项目中创建BigIntegerDemo类,在类的主方法中创建BigInteger类的实例对象,用该对象的各种方法实现大整数的加减乘除和其他运算,并输出运算结果。
package digitalprocessing;
import java.math.BigInteger;
public class BigIntergerDemo {
public static void main(String[] args) {
BigInteger bigInstance=new BigInteger("16");
//实例化一个数字
//取该大数字加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());
}
}
运行结果如图: