Factorial function produces wrong result for 21! and above

时光怂恿深爱的人放手 提交于 2019-12-12 12:06:54

问题


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?


回答1:


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.




回答2:


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.




回答3:


The maximum value that an long can take in Java is 9,223,372,036,854,775,807 and it overflows after 20!.

You should use BigInteger for computing factorials.

For example:

    BigInteger n = BigInteger.ONE;
    for (int i=1; i<=20; i++) {
        n = n.multiply(BigInteger.valueOf(i));
        System.out.println(i + "! = " + n);
    }



回答4:


It all seems ok up to the long capacity. And why are you using Math.abs() ?




回答5:


It's not obviously erratic. see here. You're pretty good up to 20. after that, I'd start looking at the max value of a long (9223372036854775807).



来源:https://stackoverflow.com/questions/13282402/factorial-function-produces-wrong-result-for-21-and-above

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!