首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

使用数组计算大数的阶乘解决办法

2012-12-20 
使用数组计算大数的阶乘解决方法在计算阶乘问题时,当数值稍微大一些,结果就会变得非常大,这样导致java或者

使用数组计算大数的阶乘解决方法
在计算阶乘问题时,当数值稍微大一些,结果就会变得非常大,这样导致java或者C的内置数据类型无法容纳

计算的结果,这里使用数组将计算结果每一位都存储在数组的每个元素中,可以根据实际的需要扩大数组大小

以容纳更长的结果。话不多说,完整代码如下:


使用数组计算大数的阶乘解决方法package algorithm;public class PowWithArray { private int[] assistArray; //使用此数组存储结果,每个int类型的数组存储0-9的数据  public PowWithArray() {  assistArray = new int[200];  assistArray[0] = 1; }  public int[] getAssistArray() {  return assistArray; }  public int calculatePowWithArray(int number) {  int maxIndex = 0;  int tempMaxIndex = 0; // 记录当前占用的最大位数,即目前的结果位数  for(int i=2;i<=number;i++) {   for(int j=0;j<=maxIndex;j++) {    assistArray[j]*=i;   }   for(int j=0;j<=maxIndex;j++) {    int temp = assistArray[j];    int index = j;    if(temp>=10) {     while(temp>=10) {      if(index==j) {       assistArray[index] = temp;      } else {       assistArray[index]+= temp;      }      index++;      temp/=10;     }     assistArray[index] += temp;     if(tempMaxIndex<index) {      tempMaxIndex = index;     }    }else{     assistArray[index] = temp;    }   }   maxIndex = tempMaxIndex;  }  return maxIndex; }  public static void main(String []args) {  PowWithArray calculateMe = new PowWithArray();  int maxIndex = calculateMe.calculatePowWithArray(23); //测试23!,结果为 25852016738884976640000  System.out.println("Result is :");  for(int i=maxIndex;i>=0;i--) {   System.out.print(calculateMe.getAssistArray()[i]);  } }}

热点排行