我寫了下面的Java代碼遞歸地計算從1到30的數字階乘。出於某種原因,輸出與results here不匹配的數字大於20.我很驚訝地看到負數。遞歸函數計算階乘失敗後20
代碼
class Test {
public static Long factorial(Long number) {
if(number == 1){
return 1L;
}else{
return number*factorial(number-1);
}
}
public static void main(final String... arguments){
for(Long number=1L;number<=30;number++){
System.out.println("Factorial of " + number + " : " + factorial(number));
}
}
}
輸出
Factorial of 1 : 1
Factorial of 2 : 2
Factorial of 3 : 6
Factorial of 4 : 24
Factorial of 5 : 120
Factorial of 6 : 720
Factorial of 7 : 5040
Factorial of 8 : 40320
Factorial of 9 : 362880
Factorial of 10 : 3628800
Factorial of 11 : 39916800
Factorial of 12 : 479001600
Factorial of 13 : 6227020800
Factorial of 14 : 87178291200
Factorial of 15 : 1307674368000
Factorial of 16 : 20922789888000
Factorial of 17 : 355687428096000
Factorial of 18 : 6402373705728000
Factorial of 19 : 121645100408832000
Factorial of 20 : 2432902008176640000
Factorial of 21 : -4249290049419214848
Factorial of 22 : -1250660718674968576
Factorial of 23 : 8128291617894825984
Factorial of 24 : -7835185981329244160
Factorial of 25 : 7034535277573963776
Factorial of 26 : -1569523520172457984
Factorial of 27 : -5483646897237262336
Factorial of 28 : -5968160532966932480
Factorial of 29 : -7055958792655077376
Factorial of 30 : -8764578968847253504
可能有人請幫助我正確計算階乘高達30?
查找溢出...... – brso05
這是一個整數溢出問題。嘗試使用BigInteger。 – luizfzs
你有一個溢出的情況下繼續。 – Chris