Recursive factorial method returning some negative

2019-02-23 08:32发布

问题:

This is my factorial method:

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

And this is what calls this recursive factorial method:

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

So far so good, the output seems correct at first but some factorials are negative instead of positive:

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 and 24 are negative, why is this happening? Is this some kind of "divide by 0" paradox?

回答1:

You are overflowing the long. You need to think of it in terms of the binary number that contains the long value. As soon as you add 1 to the maximum positive value that the long can contain, it rolls to the negative minimum.

You might want to read this for a full understanding. http://en.wikipedia.org/wiki/Two%27s_complement

In Java you can use BigInteger for bigger values http://docs.oracle.com/javase/1.4.2/docs/api/java/math/BigInteger.html