JAVA中计算阶乘的例子详解

原创|其它|编辑:郝浩|2009-08-19 13:45:22.000|阅读 1044 次

概述:在JAVA中如何计算阶乘?本文为您提供了4个计算阶乘的例子。

# 界面/图表报表/文档/IDE等千款热门软控件火热销售中 >>

  这里有四个关于计算阶乘的,难度依次提升,全部通过测试。

  这应该是基本代码了,与之共勉。

  这是利用简单的循环相乘制造的阶乘。

  public class Factorial {
  public static int factorial(int x) {
  if (x < 0) {
  throw new IllegalArgumentException("x must be>=0");
  }
  int fact = 1;
  for (int i = 2; i <= x; i++) {
  fact *= i;
  }
  return fact;
  }
  public static void main(String args[]) {
  System.out.print(factorial(10));
  }
  }

  这个是利用递归算法制成的。

  public class factorial2 {
  public static int factorial2(int x) {
  if (x < 0) {
  throw new IllegalArgumentException("x must be>=0");
  }
  if (x <= 1) {
  return 1;
  } else
  return x * factorial2(x - 1);
  }
  public static void main(String args[]) {
  System.out.print(factorial2(10));
  }
  }

  这个是数组添加的方法制成的,可以计算更大的阶乘。

  public class Factorial3 {
  static long[] table = new long[21];
  static {table[0] = 1; }
  static int last = 0;
  public static long factorial(int x) throws IllegalArgumentException {
  if (x >= table.length) {
  throw new IllegalArgumentException("Overflow; x is too large.");
  }
  if (x <= 0) {
  throw new IllegalArgumentException("x must be non-negative.");
  }
  while (last < x) {
  table[last + 1] = table[last] * (last + 1);
  last++;
  }
  return table[x];
  }
  public static void main(String[] args) {
  System.out.print(factorial(17));
  }
  }

  最后一个是利用BigInteger类制成的,这里可以用更大的更大的阶乘。
  
  import java.math.BigInteger;
  import java.util.*;
  public class Factorial4{
  protected static ArrayList table = new ArrayList();
  static{ table.add(BigInteger.valueOf(1));}
  public static synchronized BigInteger factorial(int x){
  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);
  }
  public static void main(String[] args) {
  System.out.print(factorial(17));
  }
  }


标签:

本站文章除注明转载外,均为本站原创或翻译。欢迎任何形式的转载,但请务必注明出处、不得修改原文相关链接,如果存在内容上的异议请邮件反馈至chenjj@evget.com

文章转载自:网络转载

为你推荐

  • 推荐视频
  • 推荐活动
  • 推荐产品
  • 推荐文章
  • 慧都慧问
扫码咨询


添加微信 立即咨询

电话咨询

客服热线
023-68661681

TOP