BigIntegerMath factorial() function | Guava | Java The method factorial(int n) of Guava's BigIntegerMath class is used to find the factorial of the given number. It returns n!, that is, the product of the first n positive integers.
Make another recursive method and call it from main . Show activity on this post. Create a method say getFactorial(int num) as follows. Move your for loop inside that method and call that method from main.
Example: Factorial of a Number Using Recursion Initially, the multiplyNumbers() is called from the main() function with 6 passed as an argument. Since 6 is greater than or equal to 1, 6 is multiplied to the result of multiplyNumbers() where 5 (num -1) is passed.
Apache Commons Math has a few factorial methods in the MathUtils class.
public class UsefulMethods {
public static long factorial(int number) {
long result = 1;
for (int factor = 2; factor <= number; factor++) {
result *= factor;
}
return result;
}
}
Big Numbers version by HoldOffHunger:
public static BigInteger factorial(BigInteger number) {
BigInteger result = BigInteger.valueOf(1);
for (long factor = 2; factor <= number.longValue(); factor++) {
result = result.multiply(BigInteger.valueOf(factor));
}
return result;
}
I don't think it would be useful to have a library function for factorial. There is a good deal of research into efficient factorial implementations. Here is a handful of implementations.
Bare naked factorials are rarely needed in practice. Most often you will need one of the following:
1) divide one factorial by another, or
2) approximated floating-point answer.
In both cases, you'd be better with simple custom solutions.
In case (1), say, if x = 90! / 85!, then you'll calculate the result just as x = 86 * 87 * 88 * 89 * 90, without a need to hold 90! in memory :)
In case (2), google for "Stirling's approximation".
Use Guava's BigIntegerMath
as follows:
BigInteger factorial = BigIntegerMath.factorial(n);
(Similar functionality for int
and long
is available in IntMath
and LongMath
respectively.)
Although factorials make a nice exercise for the beginning programmer, they're not very useful in most cases, and everyone knows how to write a factorial function, so they're typically not in the average library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With