Error factoring method

I am trying to get the factor value of 66 , but my method gives me the output 0 . But whenever I try to get factorial 5 , it leads to 120 . Can someone tell me why?

public static int factorial(int n) { if (n == 1) return n; return n * factorial(n - 1); } 
+4
source share
8 answers

Of course, factorials become very large, very fast. You overflow the boundaries of int very quickly ... and at some point you will be multiplied by enough coefficients to get an overflow to 0, which then will keep the value at 0 forever.

According to a quick Google search of 66, the factorial is 5.44344939 × 10 92 which significantly exceeds int , or even long or decimal . You can get a double to handle this - you will lose enormous accuracy, and it will also accumulate very quickly, but at least it will not overflow ...

+6
source

66! doesn't fit in int . Use BigInteger .

+4
source

Your method overflows. See the following example:

 static void Main(string[] args) { Console.WriteLine(factorial(66)); } public static int factorial(int n) { if (n == 1) return n; var result = n * factorial(n - 1); Console.WriteLine("{0} : {1}", n, result); return result; } 

This example prints the results of each iteration.

You see that at some point the result becomes 0 , which means that each iteration from this point becomes n * 0 .

You can try using BigInteger . This will give the correct result. Calculate factorials in C # contains additional information about this.

+4
source

The problem is that factorial 66 is the way to go big to fit into int . I think that we will also have a way to fit in long .

As an example, factorial(20) will return 2432902008176640000

+2
source

The factorial 50 is 3.0414093202 × 1064, which already displays what int may contain.

Use long or BigInteger for this.

+2
source

You get a numerical overflow, 66! ~ = 5e92, which may be more than int . In addition, factorials are better calculated using a for loop.

+1
source

About 13 or 14 is the largest number whose factorial is int ... If you switch to long, it will be 18 or 19, if I remember correctly. If you want to have big numbers, you had to write your own large arithmetic library or use the existing one :)

+1
source

You need to use the appropriate data type.

In this case, the Big Integer data type is probably the best person to see how quickly the numbers get real.

This is how you use this data type.

pic1

Right-click on your project, select the menu for adding links.

pic2

Find the system.numerics library and add it.

pic3

Then you add the use clause to your code.

pic4

And then you can initialize the variable with the keyword, as usual.

0
source

All Articles