The factorial function gives the wrong result for 21! and higher

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

The above code initializes the factorial method below:

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

The following output is also generated:

 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 

Result for 21! (this should be 51 090 942 171 709 440 000), and the result becomes completely bent for 22! and higher. Can someone explain why?

+4
source share
5 answers

With a long one, you can represent between -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 ( source ) since factorial will soon pass this range, you will begin to get errors.

+2
source

Values ​​become unstable for the 21st value and higher, because the true value is too large for long . If you need large numbers, use BigInteger .

+6
source

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

You must use BigInteger to calculate factorials.

For instance:

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

Everything looks fine to the long level. And why are you using Math.abs ()?

0
source

This is not obviously unstable. see here . After that, you will be fine until 20. After that, I will start to look at the maximum value of the long (9223372036854775807).

0
source

Source: https://habr.com/ru/post/1444721/


All Articles