Java利用BigInteger類求大數階乘運算
阿新 • • 發佈:2019-01-07
進行大數運算,用到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秒。