站内搜索: 请输入搜索关键词

当前页面: 开发资料首页Java 专题从键盘获取数据计算大的阶乘

从键盘获取数据计算大的阶乘

摘要: 从键盘获取数据计算大的阶乘

</td> </tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width="735" height="24" border="0"> <tr> <td> </td> </tr> </table>
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实例》有改动。
</td> </tr> <tr>


↑返回目录
前一篇: 使用java.util.Timer
后一篇: 应用JUnit实施单元测试(节选)