BigInteger.valueOf() limits
Solution 1
The BigInteger
class itself is used to represent immutable arbitrary-precision integers. Meaning it can represent integers of any size (limited of course by the memory on your computer).
However the valueOf
method returns a BigInteger
whose value is equal to that of the specified long. So a BigInteger
created in this way by definition can only be a large as Long.MAX_VALUE
BigInteger
objects created by the other methods and constructors of the BigInteger
class can of course be larger than Long.MAX_VALUE
.
Take for example the code snipped below:
BigInteger big1 = BigInteger.valueOf(Long.MAX_VALUE);
BigInteger big2 = BigInteger.valueOf(Long.MAX_VALUE);
BigInteger big3 = big1.add(big2);
The BigInteger
named big3
is larger than Long.MAX_VALUE
even though its constituent parts were created using the valueOf
method.
Solution 2
BigInteger
's valueOf()
method thakes a long
as its sole parameter. So the maximum number you can pass to it is the maximum a long
can represent (2^63-1 = 9223372036854775807
).
Admin
Updated on June 15, 2022Comments
-
Admin about 2 years
Does valueOf for BigInteger have any limitations ? I'm not sure but read somewhere, that given number can be of length = long only.