I need the factorial of 100, I realize that I need to look for another alternative, could you help?
public class Main {
public static void main(String[] args) {
System.out.println(factorial(100));
}
public static long factorial(long num) {
if (num <= 1)
return num;
return num * factorial(num-1);
}
}
The problem is not the recursion but that the value of the factorial of 100 is too large to enter the bits of a
long
, either in Java or another programming language that handles this type of data. Note that the maximum value of along
in Java is0x7fffffffffffffffL
o 9223372036854775807In Java, this can be resolved using
BigInteger
, although it does reduce application performance.Example:
Result:
The recursion problem arises when you do calculations already calculated previously, the recursion calculates and repeats calculations until reaching the base case.
Better I explain it with an image, the factorial(3) and the factorial(4) with recursion:
According to the image, to obtain the y
factorial(3)
is calculated , then to obtain the it also calculates the y , then the recursion repeats calculations, that is very bad for execution times .factorial(2)
factorial(1)
factorial(4)
factorial(2)
factorial(1)
Why not save the results and use them whenever you need? So they will no longer be calculated over and over again, you only calculate once and that's it.
according to comments, good observations!!!:
You already had the iterative code yourself, you just needed to change the data type from long to
double
since the factorial you were looking for is too big tolong
That returns:
9.332621544394418E157