介绍

java中用于操作大数的类主要有俩种 第一个是BigInteger,代表大整数。第二个是BigDecimal,代表大浮点数。两种类的操作方法类似

基本用法

Scanner in = new Scanner(System.in);
BigInteger a = in.nextBigInteger();
BigInteger b = in.nextBigInteger();

1.更改为大数数据类型

String s = "12345678987654321"
BigInteger a = new BigInteger(s);//把字符串转换为大数类型


int a =1234567;
BigInteger a = BigInteger.valueOf(a);//将int型转换为大数类型


String s = "12345678987654321";
BigInteger a =BigInteger.valueOf(s,10);//将字符串转换成10进制的大数

2.大整数的四则运算

a.add(b)    //求a+b 加法

a.subtract(b)  //求a-b 减法

a.divide(b)   //求a/b 除法

a.multiply(b)  //求a*b 乘法

3.大整数比较大小

a.equals(b);  //如果a b相等 返回true 否则返回false

if(a.equals(a.max(b)))   //如果a等于a和b中的较大者 即a>b 否则a<b

4.常用方法

a.mod(b)  //求余数即a%b

a.gcd(b)   //求最大公约数

a.max(b)  //求最大值

a.min(b)   //求最小值

a.pow(b)  //求a^b的大数

5.求大数的长度

a.toString().length();

6.各种方法的测试代码

import java.math.BigInteger;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
	Scanner in = new Scanner(System.in);
	BigInteger a = in.nextBigInteger();
	BigInteger b = in.nextBigInteger();
	BigInteger c = in.nextBigInteger();
	int d=in.nextInt();
	//加法
	System.out.println(a+"+"+b+"="+a.add(b));

	//减法
	System.out.println(a+"-"+b+"="+a.subtract(b));

	//除法
	System.out.println(a+"/"+b+"="+a.divide(b));

	//乘法
	System.out.println(a+"*"+b+"="+a.multiply(b));

	//取模
	System.out.println(a+"%"+b+"="+a.remainder(b));
	           
	//快速幂取模
	System.out.println("("+a+"^"+b+")"+"%"+c+"="+a.modPow(b,c));

	//比较两个数字的大小,小于返回-1,大于返回1,等于0的时候返回0
	System.out.println(a.compareTo(b));

	//n次幂的运算
	System.out.println(a+"^"+d+"="+a.pow(d));

	//返回较小的数
	System.out.println(a.min(b));

	//返回较大的数
	System.out.println(a.max(b));
	
	//返回该类型的数字的值
	System.out.println(a.intValue());

	//返回最大公约数
	System.out.println(a.gcd(b));
	
	//返回c进制的字符串(进制的转换)
	System.out.println(a.toString(d));

	//返回数字的绝对值
	System.out.println(a.abs());
	 
	//返回当前大整数的相反数
	System.out.println(a.negate());
	 
	in.close();
}
}