问题分析:问题要求对输入的正整数n,计算n!的准确值,而n!的增长速度高于指数增长的速度,所以这是一个高精度计算问题。
请看下面两个例子:9!=362 880
100!= 93 326 215 443 944 152 681 699 238 856 266 700 490 715 968 264 381 621 468 592 963 895 217 599 993 229 915 608 941 463 976 156 518 286 253 697 920 827 223 758 251 185 210 916 864 000 000 000 000 000 000 000 000
对于这样的数,我们必须采用数组来存储。
如果采用我们平常的递归方法,当n值过大时候,结果会溢出。代码如下:
package com.intg;
/*
* 这种方法容易溢出
*/
public class Hierarchy {
public static int f(int n){
if(n == 1){
return 1;
}
else{
return n*f(n-1);
}
}
public static void main(String[] args) {
System.out.println(f(12));
}
}
这种方法只适合当n小于13的值才适合,这是我测试的一个上限值。
当n>=13时,不适合用上述方法,这个时候就需要在中间计算过程中,将中间结果用数组保存起来,改进的递归运算:
package com.intg;
public class Hierarchy_1 {
public static int[] f(int n){
int A[] = new int[160];
if(n == 1){
A[0] = 1;
}
else{
int d = 0,b;
int B[] = f(n-1);
int len = B.length;
// System.out.println("len;"+len);
for(int i = 0,j = 0; i <= len-1; i ++,j++){
// System.out.println(j+":"+B[i]);
b = B[i] *n +d;
A[j] = b%10;
d = b/10;
}
while(d != 0){
A[len] =d%10;
d = d / 10;
len++;
}
return A;
}
return A;
}
public static void main(String[] args) {
int B[]= f(100);
System.out.println("B:"+B.length);
for(int i = B.length-1 ; i >= 0 ; i--){
// if(B[i] != 0){
System.out.print(B[i]);
// }
}
}
}
这种方法局限是不知道如何来确定中间过程中的数组个数,在这里我就采用100!的最大个数来定的,任意正整数的结果都是160位,所以当维数很小时,都是用0补上。
这种方法还是很有局限,希望大家指正。