Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Factorial function produces wrong result for 21! and above

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

The code above initializes the factorial method below:

public static long factorial(int num1)
{
    if (num1 == 0)
        return 1;
    else
        return Math.abs(num1 * factorial(num1 - 1));
}

As so the following output is created:

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

The result for 21! is wrong (it should be 51,090,942,171,709,440,000), and the result becomes completely haywire for 22! and above. Can anyone explain why?

like image 917
Matt Andrzejczuk Avatar asked Dec 21 '22 13:12

Matt Andrzejczuk


2 Answers

The values become erratic for the 21st value and above, because the true value is is too big for a long. If you need bigger numbers, use BigInteger.

like image 160
Cory Kendall Avatar answered Dec 25 '22 23:12

Cory Kendall


With long you can represent between -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 (source)so as soon the factorial pass that range you start to get errors.

like image 37
dreamcrash Avatar answered Dec 25 '22 22:12

dreamcrash