TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
java.math.BigInteger类表示了任意大的整数值,并提供了在这些大数上进行算术运算的方法,下面例子使用了BigInteger类来计算任意数的阶乘,第一个类是测试类,计算阶乘的方法放在第二个类,ArrayList类型的变量table用来缓存被计算出来的阶乘,在这里你不能使用大小固定的数组作缓存器,阶乘一旦计算出来就会被存储以备后用。
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class FactQuoter{
public static void main(String args[]) throws IOException{
BufferedReader in=
new BufferedReader(new InputStreamReader(System.in));
for(;;){
System.out.print("FactQuoter>");
String line=in.readLine();//读用户从键盘的输入
if((line==null)||line.equals("quit")) break;
try{
int x=Integer.parseInt(line);
System.out.println(x+"!="+Factoria.factorial(x)); //输出结果
}catch(Exception e){
System.out.println("Invalid Input");
}
}
}
}
class Factoria{ //计算大的阶乘的类。
protected static ArrayList table=new ArrayList();
static{
table.add(BigInteger.valueOf(1));
}
public static synchronized BigInteger factorial(int x){
if(x<0) throw new IllegalArgumentException("x must be non-negative.");
for(int size=table.size(); size<=x;size++){
BigInteger lastfact=(BigInteger)table.get(size-1);
BigInteger nextfact=lastfact.multiply(BigInteger.valueOf(size));
table.add(nextfact); //缓存已计算的阶乘
}
return (BigInteger)table.get(x);
}
}
程序运行的结果:
C:java>java FactQuoter
FactQuoter>45
45!=119622220865480194561963161495657715064383733760000000000
FactQuoter>60
60!=8320987112741390144276341183223364380754172606361245952449277696409600000000000000
FactQuoter>quit
本文摘自:中国电力出版社《java实例》有改动。 |
|