I have the following code from my textbook for figuring out factorial:
import java.math.*;
public class LargeFactorial {
public static void main(String[] args) {
System.out.println("50! is \n" + factorial(50));
} public static BigInteger factorial(long n) {
BigInteger result = BigInteger.ONE;
for (int i = 1; i <= n; i++)
result = result.multiply(new BigInteger(i +""));
return result;
}
However, I really don't understand new BigInteger(i +"")
. Why they put +""
in the constructor?I mean we are not multiplying an empty String and it does not make any sense either.Please explain.
It's just calling the BigInteger(String)
constructor, because there isn't a constructor taking an int
. Using string concatenation is a nasty way of converting an int
to a String
, but it will work.
A cleaner approach IMO would be to use BigInteger.valueOf(long)
:
result = result.multiply(BigInteger.valueOf(i));
(Given both of these issues, I'd be slightly wary of the quality of your textbook...)
See more on this question at Stackoverflow