课外天地 李树青学习天地Java程序语言课件 → [原创]关于数据的阶乘计算效率低的问题解决方法


  共有20362人关注过本帖树形打印复制链接

主题:[原创]关于数据的阶乘计算效率低的问题解决方法

帅哥哟,离线,有人找我吗?
qiuweiwei
  1楼 博客 | 信息 | 搜索 | 邮箱 | 主页 | UC


加好友 发短信
等级:新手上路 帖子:2 积分:254 威望:0 精华:0 注册:2011/3/18 15:08:56
[原创]关于数据的阶乘计算效率低的问题解决方法  发帖心情 Post By:2011/3/30 15:18:23 [显示全部帖子]

关于老师上课讲的数据的阶乘计算效率低的问题,找了一个比较好的方法, 不过能计算的数最大为 9272  不过效率非常高,9272这个数的阶乘计算时间大约为1秒

贴下代码,有问题的话大伙一起讨论下,联系方法 qww_java@hotmail.com

 

package java_jichuzhishi_1;

import java.math.BigInteger;
import java.util.ArrayList;

public class Factorial4 {

 /*
  * 这个版本的程序使用了任意精度的整数 因此对于所能计算的值没有上限 他使用arraylist对象来缓存所计算出的值,而没有使用一个固定大小的数组
  * arraylist与数组很相似,但是arraylist可以任意扩展大小 factorial()方法声明为 同步,从而可以安全的用于多线程中
  */
 protected static ArrayList table = new ArrayList();// 创建缓存
 static {
  table.add(BigInteger.valueOf(1)); //初始化第1个数
 }

 // factorial()方法使用在一个arraylist中缓存的bigintger
 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);

 }
}
}

 

 

 

package java_jichuzhishi_1;

import java.io.*;

public class FactQuoter {

 /**
  * 程序将在用户交互式地输入值时显示出相应数的阶乘
  */
 public static void main(String[] args) throws IOException {
  // 从用户处读取文本行使用的方法
  BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  for (;;) {
   System.out.println("输入");
   // 从用户读取一行
   String line = in.readLine();
   // 如果到达文件结尾或者输入“quit”,退出
   if ((line == null) || line.equals("quit"))
    break;
   int x = Integer.parseInt(line);
   System.out.println(x + "!=" + Factorial4.factorial(x));
  }
 }

}

 

 


 回到顶部