java.math 包中有这样两个类:BigInteger 和 BigDecimal 。
这两个类用于在基本的整数和浮点精度(int、double、float等等)不能够满足题目要求的时候,他们可以处理包含任意长度数字序列的数值。
其中BigInteger类实现任意精度的整数运算;BigDecimal 实现了任意精度的浮点数运算。
用法一、
可以使用静态方法(valueOf()方法)将普通的数值转换为大数值类:
BigInteger num = BigInteger.valueOf( 100 );
但是这种方法不能直接地让熟知的算术运算符处理大数值,而必须要使用大数值类中特定的两种方法去实现(add()和multiply()方法):
BigInteger c = a.add(b); //c=a+b
int b = 9;
long m = 3
BigInteger a=BigInteger.valueOf(m); // valueOf() 中变量必须为int 或 long 型
BigInteger c=a.add(BigInteger.valueOf(b)); //add() 和 multiply() 方法中变量必须是BigInteger()类型
BigInteger d = c.multiply(b.add(BigInteger.valueOf(2))); // d=c*(b+2)
注:Java中不像C(C++)语言那样有提供运算发重载功能;我们要想实现像“+”或“乘”那样的运算符,就必须要调用其中的类方法进行运算;Java中为只为字符串的连接重载了+运算符,没有重载其他的运算符,也没有给Java程序员在自己的类中重载运算符的机会。
/*
求两个不超过 200 位的非负整数的和?
要做这题,以前的基本数值运算很难行得通的,这就用到了大数值运算类,通过下面我给出的程序可以看出,很方便的就可以通过系统测试。
*/
import java.util.*;
import java.math.*;
public class Main{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
BigInteger m = in.nextBigInteger();
BigInteger n = in.nextBigInteger();
BigInteger sum = m.add(n);
System.out.print(sum);
}
}
> java.math.BigInteger 方法类有:
add(BigInteger other) //返回和值
subtract(BigInteger other) //返回差值
multiply(BigInteger other) //返回乘积值
divide(BigInteger other) //返回商值
mod(BigInteger other) //返回余数
> java.math.BigDecimal 方法类有:
add(BigInteger other) //返回和值
subtract(BigInteger other) //返回差值
multiply(BigInteger other) //返回乘积值
divide(BigInteger other) //返回商值
mod(BigInteger other) //返回余数
int compareTo(BigInteger other) //若这两个大实数相等,返回0;若这个实数小于另一个大实数,返回负数;否则,返回正数
static BigDecimal valueOf(long x)
static BigDecimal valueOf(long x,int scale) //返回值为x或x/10^scale 的一个大实数