hello.Lyn 发表于 2013-1-26 14:01:06

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

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

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

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


使用数组计算大数的阶乘解决方法package algorithm;public class PowWithArray { private int[] assistArray; //使用此数组存储结果,每个int类型的数组存储0-9的数据public PowWithArray() {assistArray = new int;assistArray = 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*=i;   }   for(int j=0;j<=maxIndex;j++) {    int temp = assistArray;    int index = j;    if(temp>=10) {   while(temp>=10) {      if(index==j) {       assistArray = temp;      } else {       assistArray+= temp;      }      index++;      temp/=10;   }   assistArray += temp;   if(tempMaxIndex<index) {      tempMaxIndex = index;   }    }else{   assistArray = temp;    }   }   maxIndex = tempMaxIndex;}return maxIndex; }public static void main(String []args) {PowWithArray calculateMe = new PowWithArray();int maxIndex = calculateMe.calculatePowWithArray(23); //测试23!,结果为 25852016738884976640000System.out.println("Result is :");for(int i=maxIndex;i>=0;i--) {   System.out.print(calculateMe.getAssistArray());} }}
页: [1]
查看完整版本: 使用数组计算大数的阶乘解决方法