Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive factorial method returning some negative numbers

Tags:

java

factorial

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?

like image 364
Matt Andrzejczuk Avatar asked Nov 01 '12 16:11

Matt Andrzejczuk


People also ask

Can you do factorial with negative numbers?

Presently, factorials of real negative numbers and imaginary numbers, except for zero and negative integers are interpolated using the Euler's gamma function. In the present paper, the concept of factorials has been generalised as applicable to real and imaginary numbers, and multifactorials.

What is the recursive formula for factorial?

The factorial function can be rewritten recursively as factorial(n) = n × factorial(n – 1). The factorial of 1 is simply 1.


1 Answers

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

like image 175
Erik Nedwidek Avatar answered Oct 14 '22 04:10

Erik Nedwidek