我需要最多写23个阶乘!我最多可以做20个阶乘!但之后我迷路了,因为人数太大了。 我无法使用BigInteger。
我必须存储最右边的数字为0,所以示例输出:
10! = 3628800-> fac = 36288,num10 = 2
23! = 2585..976640000-> fac = 2585..97664,num10 = 4
import java.util.Scanner;
public class Factorial10{
public static void main(String[] args){
long fac; // long: factorial is very large
long pre_fac; // to check overflow
int i, n;
int num10;
Scanner sc = new Scanner(System.in);
System.out.print("n? ");
n = sc.nextInt();
// Start from fac = 0! = 1
for(i= 1, fac= 1L; i<n; i++){
pre_fac = fac;
fac *= i;
// Checking if it is multiple of 10,
// and adjust the variables fac and num10
//while((fac % 10) == 0){
// num10++;
// fac /= 10;
//}
// check if overflowed
if(pre_fac != fac /i){
System.out.println("Overflowed at " + i + "! = " + fac);
fac = pre_fac; // roll back to the previous, unoverflowed
break;
}
}
System.out.println((i-1) + "! = " + fac + "(fac = , num10 = )");
}
}
```
选择float,而不是long
double fac;
double pre_fac;