java 大数的简单介绍及应用

前言

在某些情况下,我们需要计算一些很大的数,比如求一个数的阶乘,这样的场景下,long 也不能胜任这样的大数的表示。
所幸,java为我们提供的强大且方便的大数类供我们使用。

BigInteger类介绍

声明&赋值方式

声明:BigInteger bi;
赋值:
1、 bi=BigInteger.valueOf(100); //直接赋值法
2、 Scanner in= new Scanner(System.in);
bi=in.nextBigInteger(); //从键盘读取
3、 bi=new BigInteger(“100”); //调用构造方法,还有其他构造方法,请自行百度

三个常量

BigInteger.ZERO, BigInteger.ONE, BigInteger.TEN 分别对应 0,1,10 。

常用的方法

BigInteger a,b;
add 两数相加:a.add(b) // 下列方法用法和加法类似
subtract 减
multiply 乘
divide 除
mod 取模
pow 乘方
equals 判断是否相等
compareTo 判断大小 a.compareTo(b) a>b 返回1; a=b 返回0 ; a<b 返回-1;

实例

用大数类求任意整数的阶乘(用递归实现)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.math.BigInteger;
import java.util.Scanner;

public class Fac {
static BigInteger fac(BigInteger n){
if(n.equals(BigInteger.ZERO)||n.equals(BigInteger.ONE)) return BigInteger.ONE; // if(n==1||n==0) return 1;
else return n.multiply(fac(n.subtract(BigInteger.ONE))); // else return n*fac(n-1);
}

public static void main(String[] args) {
BigInteger n;
Scanner in = new Scanner(System.in);
System.out.println("输入整数:");
n=in.nextBigInteger();
System.out.println(n+" 的阶乘为: "+fac(n));
}
}