Java利用BigInteger类求大数阶乘运算
进行大数运算,用到BigInteger类,首先介绍一下这个类
方法 | 描述 |
---|---|
public BigInteger (String var) | 将一个字符串变为BigInteger类型的数据 |
public BigInteger add(BigInteger val) | 加法 |
public BigInteger subtract(BigInteger val) | 减法 |
public BigInteger multiply(BigInteger val) | 乘法 |
public BigInteger subtract(BigInteger val) | 除法 |
import java.math.BigInteger;
import java.util.Scanner;
public class BigFlag{
public static void main(String[] args) {
long startTime=System.currentTimeMillis();
BigInteger num=new BigInteger("1");
BigInteger flat=new BigInteger("1");
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
for (int i = 0; i < n; i++) {
flat=flat.multiply(num);
num=num.add(new BigInteger("1"));
}
System.out.println(n+"!="+flat);
System.out.println("共"+flat.toString().length()+"位");
long endTime=System.currentTimeMillis();
System.out.println("计算"+n+"!一共用了"+(double)(endTime-startTime)/1000+"秒");
}
}
以100000的阶乘为例,一共用了8秒。