Java – which data type or data structure to choose to calculate the factorial of 100?
•
Java
I want to write a program to evaluate the factorial of a given integer
The following basics I wrote the following code in Java:
long fact(int num){ if(num == 1) return 1; else return num*fact(num-1); }
But then I realized that for many integer inputs, the result may not be what I expected, so for the test, the input is 100
I doubt it's true because I get a result of "0" (the reason and result may be beyond the long-term range)
So I'm just curious and eager to know how to make my program suitable for input < = 150 I appreciate any effective solution in C programming language or Java
Solution
BigInteger is your class It can store integers of any size
static BigInteger fact(BigInteger num) { if (num.equals(BigInteger.ONE)) return BigInteger.ONE; else return num.multiply(fact(num.subtract(BigInteger.ONE))); }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码