递归阶乘方法返回一些负数(Recursive factorial method returning

2019-07-03 11:49发布

这是我的阶乘方法:

public static long factorial(int num1) {
    if (num1 <= 1) 
        return 1; 
    else
        return num1 * factorial(num1 - 1);
}

这就是调用这个递归阶乘方法:

for (i = 0; i <= 25; i++)
    System.out.printf  ("%d !=  %,d\n", i, factorial (i));

到目前为止好,输出似乎起初正确的,但一些阶乘是负的,而不是积极的:

OUTPUT:
0 !=  1
1 !=  1
2 !=  2
3 !=  6
4 !=  24
5 !=  120
6 !=  720
7 !=  5,040
8 !=  40,320
9 !=  362,880
10 !=  3,628,800
11 !=  39,916,800
12 !=  479,001,600
13 !=  6,227,020,800
14 !=  87,178,291,200
15 !=  1,307,674,368,000
16 !=  20,922,789,888,000
17 !=  355,687,428,096,000
18 !=  6,402,373,705,728,000
19 !=  121,645,100,408,832,000
20 !=  2,432,902,008,176,640,000
21 !=  -4,249,290,049,419,214,848
22 !=  -1,250,660,718,674,968,576
23 !=  8,128,291,617,894,825,984
24 !=  -7,835,185,981,329,244,160
25 !=  7,034,535,277,573,963,776

21,22和24是负的,为什么会出现这种情况? 这是某种悖论“0分”的?

Answer 1:

您溢满长。 你需要在包含长值的二进制数来考虑它。 只要你加1的最大正值,长期可以包含,它滚到负的最小值。

你可能想读这对于一个充分的认识。 http://en.wikipedia.org/wiki/Two%27s_complement

在Java中,你可以使用的BigInteger更大的价值http://docs.oracle.com/javase/1.4.2/docs/api/java/math/BigInteger.html



文章来源: Recursive factorial method returning some negative numbers