在这里,我们详细描述下BigInteger的用法,在使用之前,我们需要导入java.math.*包
一.介绍BigInteger经常使用到的一些函数
①value.Of(参数); 这个函数的作用是将括号内的参数转换成指定的数据类型,例如以下例子
• int A=42;
• BigInteger f=BigInteger.valueOf(A);
• System.out.println("f="+f); //输出的f将会等于BigInteger型的42
• // 答案: f=42
其实还可以转成其他的类型,例如以下以下,※※※需要注意的是不重写的话,jdk1.8 版本是无法支持这种转换的※※※
• String s="12345";
• BigInteger c=BigInteger.valueOf(s);
• // 则c=12345;※※※需要注意的是不重写的话,jdk1.8 版本是无法支持这种转换的
②add()方法; 这个函数的作用是将大整数加起来,例如以下例子
• String s="12345";
• BigInteger c=BigInteger.valueOf(s);
• // 则c=12345;※※※需要注意的是不重写的话,jdk1.8 版本是无法支持这种转换的
③subtract()方法,这个函数的作用是将大整数相减,例如以下例子,运用时前者减后者
• BigInteger c=new BigInteger("5");
• BigInteger d=new BigInteger("3");
• System.out.println("d-c="+d.subtract(c));
//答案输出: d-c=-2
④multiply()方法,这个函数的作用是将大整数相乘,例如以下例子,
• BigInteger c=new BigInteger("6");
• BigInteger d=new BigInteger("3");
• System.out.println("c*d="+c.multiply(d));
//答案输出: c*d=18
⑤divide()方法,这个函数的作用是将大整数做除法,例如以下例子,
• BigInteger c=new BigInteger("6");
• BigInteger d=new BigInteger("4");
• System.out.println("c/d="+c.divide(d));
// 答案输出;c/d=1
⑥remainder()方法,这个函数的作用是将大整数取余
⑦pow(exponent)方法,这个函数的作用是将大整数取exponent的指数,例如a.pow(b)==a^b;
⑧gcd()方法,这个函数的作用是将两个大整数取最大公约数,例如a.gcd(b);
⑨abs()方法,这个函数的作用是取绝对值,例如
• BigInteger c=new BigInteger("-9");
• System.out.println(c.abs());
//答案输出: 9
⑩negate()方法,这个函数的作用是取数的相反数,例如
• BigInteger c=new BigInteger("9");
• System.out.println(c.negate());
// 答案输出: -9
⑪mod()方法; 这个函数的作用是对数进行取余 a.mod(b)=a%b=a.remainder(b);
⑫max()方法,min()方法,分别是比较两个数的大小,例如a.max(b); 取a,b中的最大值
⑬compareTo()方法这个方法是用来比较两个大整数大小的
• public void testCompare() {
• BigInteger bigNum1 = new BigInteger("52");
• BigInteger bigNum2 = new BigInteger("27");
• //1.compareTo():返回一个int型数据(1 大于; 0 等于; -1 小于)
• int num = bigNum1.compareTo(bigNum2); //1
• //2.max():直接返回大的那个数,类型为BigInteger
• // 原理:return (compareTo(val) > 0 ? this : val);
• BigInteger compareMax = bigNum1.max(bigNum2); //52
• //3.min():直接返回小的那个数,类型为BigInteger
• // 原理:return (compareTo(val) < 0 ? this : val);
• BigInteger compareMin = bigNum1.min(bigNum2); //27
•}
⑭equals()方法,判断两个大整数是否相等,例如c.equals(d) 相等就返回 true;
原文链接:https://blog.csdn.net/qq_49174867/article/details/123587380