Java BigInteger Class Example
In this article, we will discuss about Java BigInteger Class – java.math.BigInteger
and create a java biginteger example. This interesting class extends the java.lang.Number
class and implements the java.lang.Comparable
interface.
public class BigInteger extends Number implements Comparable
1. Java BigInteger Class – Introduction
All operations behave as if BigIntegers were represented in two’s-complement notation (like Java’s primitive integer types). BigInteger provides analogues to all of Java’s primitive integer operators, and all relevant methods from java.lang.Math
. Additionally, BigInteger
provides operations for modular arithmetic, GCD calculation, primality testing, prime generation, bit manipulation, and a few other miscellaneous operations.
Semantics of arithmetic operations exactly mimic those of Java’s integer arithmetic operators, as defined in The Java Language Specification. For example, division by zero throws an ArithmeticException
, and division of a negative by a positive yields a negative (or zero) remainder. All of the details in the Spec concerning overflow are ignored, as BigIntegers
are made as large as necessary to accommodate the results of an operation.
Semantics of shift operations extend those of Java’s shift operators to allow for negative shift distances. A right-shift with a negative shift distance results in a left shift, and vice-versa. The unsigned right shift operator (>>>
) is omitted, as this operation makes little sense in combination with the “infinite word size” abstraction provided by this class.
Semantics of bitwise logical operations exactly mimic those of Java’s bitwise integer operators. The binary operators (and, or, xor) implicitly perform sign extension on the shorter of the two operands prior to performing the operation.
Comparison operations perform signed integer comparisons, analogous to those performed by Java’s relational and equality operators. Modular arithmetic operations are provided to compute residues, perform exponentiation, and compute multiplicative inverses. These methods always return a non-negative result, between 0 and (modulus – 1), inclusive. Bit operations operate on a single bit of the two’s-complement representation of their operand. If necessary, the operand is sign- extended so that it contains the designated bit.
None of the single-bit operations can produce a BigInteger
with a different sign from the BigInteger
being operated on, as they affect only a single bit, and the “infinite word size” abstraction provided by this class ensures that there are infinitely many “virtual sign bits” preceding each BigInteger
.
2. Constructors
In this section we will discuss different constructors available in BigInteger
class and create a java biginteger example.
public BigInteger(byte[] val)
This constructor translates a byte array containing the two’s-complement binary representation of a BigInteger
into a BigInteger
. The input array is assumed to be in big-endian byte-order: the most significant byte is in the zeroth element
System.out.println(new BigInteger("123456789".getBytes()));
Running the above code give the output as 907507751940624169017
public BigInteger(int signum, byte[] magnitude)
This constructor translates the sign-magnitude representation of a BigInteger
into a BigInteger
. The sign is represented as an integer signum value: -1 for negative, 0 for zero, or 1 for positive. The magnitude is a byte array in big-endian byte-order: the most significant byte is in the zeroth element. A zero-length magnitude array is permissible and will result in a BigInteger
value of 0, whether signum is -1, 0 or 1.
public BigInteger(String val, int radix)
This constructor translates the String representation of a BigInteger
in the specified radix into a BigInteger
. The String representation consists of an optional minus or plus sign followed by a sequence of one or more digits in the specified radix. The character-to-digit mapping is provided by Character.digit
. The String may not contain any extraneous characters (whitespace, for example).
System.out.println(new BigInteger("123456789", Character.MAX_RADIX));
Running the above code will give the output as: 2984619134745
public BigInteger(String val)
This constructor translates the decimal String representation of a BigInteger
into a BigInteger
. The String representation consists of an optional minus sign followed by a sequence of one or more decimal digits. The character-to-digit mapping is provided by Character.digit
. The String may not contain any extraneous characters (whitespace, for example)
public BigInteger(int numBits, Random rnd)
Constructs a randomly generated BigInteger
, uniformly distributed over the range 0 to (2^numBits – 1), inclusive. The uniformity of the distribution assumes that a fair source of random bits is provided in rnd. Note that this constructor always constructs a non-negative BigInteger
public BigInteger(int bitLength, int certainty, Random rnd)
Constructs a randomly generated positive BigInteger
that is probably prime, with the specified bitLength. It is recommended that the probablePrime()
method be used in preference to this constructor unless there is a compelling need to specify a certainty.
3. Methods
In this section we will discuss the important methods in BigInteger
class and create a java biginteger example.
public static BigInteger probablePrime(int bitLength, Random rnd)
Returns a positive BigInteger
that is probably prime, with the specified bitLength. The probability that a BigInteger returned by this method is composite does not exceed 2^100
public BigInteger nextProbablePrime()
Returns the first integer greater than this BigInteger
that is probably prime. The probability that the number returned by this method is composite does not exceed 2^100. This method will never skip over a prime when searching: if it returns p, there is no prime q such that this < q < p.
final BigInteger probablePrime = BigInteger.probablePrime(9, new Random()); System.out.println("Probable prime: " + probablePrime); System.out.println("Next probable prime: " + probablePrime.nextProbablePrime());
Running the above code gets me the output as below. Please note this might change for another run but what will not change is the fact that there is no other prime number between these two.
Probable prime: 397 Next probable prime: 401
public static BigInteger valueOf(long val)
This method returns a BigInteger
whose value is equal to that of the specified long
. This static factory method is provided in preference to a (long) constructor because it allows for reuse of frequently used BigIntegers
.
System.out.println(BigInteger.valueOf(1234567890987654321L));
Running the above code will give the below output:
1234567890987654321
public BigInteger add(BigInteger val)
Returns a BigInteger
whose value is (this + val).
BigInteger first = BigInteger.valueOf(23); BigInteger second = BigInteger.valueOf(32); System.out.println(String.format("%s + %s = %s", first.toString(), second.toString(), first.add(second).toString()));
The output of the above code is 23 + 32 = 55
public BigInteger subtract(BigInteger val)
Returns a BigInteger
whose value is (this – val).
BigInteger first = BigInteger.valueOf(23); BigInteger second = BigInteger.valueOf(32); System.out.println(String.format("%s - %s = %s", second.toString(), first.toString(), second.subtract(first).toString()));
Running the above code will output 32 - 23 = 9
public BigInteger multiply(BigInteger val)
Returns a BigInteger
whose value is (this * val).
BigInteger first = BigInteger.valueOf(23); BigInteger second = BigInteger.valueOf(32); System.out.println(String.format("%s x %s = %s", first.toString(), second.toString(), first.multiply(second).toString()));
Running the above code will output 23 x 32 = 736
public BigInteger divide(BigInteger val)
Returns a BigInteger
whose value is (this / val).
BigInteger first = BigInteger.valueOf(23); BigInteger second = BigInteger.valueOf(32); System.out.println(String.format("%s / %s = %s", second.toString(), first.toString(), second.divide(first).toString()));
Running the above code will output 32 / 23 = 1
public BigInteger[] divideAndRemainder(BigInteger val)
Returns an array of two BigIntegers
containing (this / val) followed by (this % val). It returns an array of two BigIntegers
: the quotient this / val
is the initial element, and the remainder this % val
is the final element.
final BigInteger[] bigIntegers = second.divideAndRemainder(first); System.out.printf("%s / %s => Quotient: %s, Remainder: %s", second.toString(), first.toString(), bigIntegers[0].toString(), bigIntegers[1].toString());
The above code will output 32 / 23 => Quotient: 1, Remainder: 9
public BigInteger pow(int exponent)
This method returns a BigInteger
whose value is thisexponent. Note that exponent is an integer rather than a BigInteger
.
4. Conclusion
In this article we discussed the BigInteger
class in java. We looked at some of the way of constructing the BigInteger
object using constructors and factory methods. Then we discussed some of the important methods in the class.
5. Download the source code
You can download the full source code of this example here: Java BigInteger Class Example