CodeGym /Java Blog /Java Numbers /Java BigInteger Class
Author
Oleksandr Miadelets
Head of Developers Team at CodeGym

Java BigInteger Class

Published in the Java Numbers group

What is a BigInteger Class?

There are some primitive data types in Java that are used, such as int or long, to perform integer operations. However, sometimes we need to store large numbers outside the scope of such primitive data types. BigInteger Class is used for mathematical computations for very large numbers. It provides all methods from the java.lang.Math package and analogues to all of the Java’s primitive integer operators. BigInteger Class covers operations for modular arithmetic, bit manipulation, GCD calculation, and a few other operations. BigIntegers are represented in two’s-complement notation. There is no theoretical limit on how large a number can be stored because the memory is allocated dynamically. However, practically the memory is limited and we can store an integer that has the number of bits less than or equal to the Integer.MAX_VALUE. This provides a sufficiently large upper bound to store practically almost all large numbers.

How is the BigInteger Class Implemented?


import java.math.BigInteger;
To implement the BigInteger class in your code, you need to import java.math.BigInteger package.

BigInteger Class Declaration

The BigInteger class in Java is declared in the following way in java.math package:

public class BigInteger
   extends Number
      implements Comparable<BigInteger>
The BigInteger class extends the Number class and implements a Comparable interface. It is declared and defined in java.math package.

Class Constructors

Java’s BigInteger Class has many overloaded constructors. You may try and run each in the editor to see how they work.
Sr# Constructor Description
1 BigInteger(byte[] val) Translates a byte array into a BigInteger.
2 BigInteger(int signum, byte[] magnitude) Translates sign-magnitude representation into a BigInteger.
3 BigInteger(int bitLength, int certainty, Random rnd) Constructs a randomly generated positive BigInteger of the specified length.
4 BigInteger(String val) Translates decimal string representation into a BigInteger.
5 BigInteger(String val, int radix) Converts the String representation in the specified radix into a BigInteger.

Class Methods

Java’s BigInteger class has many methods, some of which are described below. In the table, ‘this’ represents the BigInteger that calls the method and ‘val’ is the argument passed to the method.
abs() It returns the absolute value of ‘thisBigInteger.
add() It returns a Biginteger by computing ‘this + val’.
subtract() It returns a Biginteger by computing ‘this - val’.
divide() It returns a Biginteger by computing ‘this / val’.
multiply() It returns a Biginteger by computing ‘this * val’.
valueOf() It returns a BigInteger value of given long.
equals() It compares equality between ‘thisBigInteger and a given object.
pow() It returns a Biginteger by computing 'thisexponent'.
min() It returns the minimum between ‘thisBigInteger and the given value.
max() It returns the maximum between ‘thisBigInteger and the given value.
mod() It returns a value for ‘this mod m’.
gcd() It returns a BigInteger that is the greatest common divisor between the absolute value of ‘this’ and the ‘passed value’.
bitCount() It returns the number of bits in the two’s-complement representation of ‘thisBigInteger.
bitLength() It returns the number of bits, excluding the sign bit, in the minimal two’s-complement representation of ‘thisBigInteger.
and() It returns a Biginteger by computing ‘this & val’.
or() It returns a Biginteger by computing ‘this | val’.
not() It returns a Biginteger by computing ‘~this’.
andNot() It returns a Biginteger by computing ‘this & ~val’.
intValue() It converts BigInteger to an int.
floatValue() It converts BigInteger to float.
longValue() It converts BigInteger to long.
doubleValue() It converts BigInteger to double.
toString() It returns the decimal string representation of BigInteger.

Example 1


import java.math.BigInteger;
public class Example1 {
    static BigInteger calculateFactorial(int val) {
        // Initialize result
        BigInteger f = BigInteger.ONE; // Or new BigInteger("1")
        // compute factorial
        for (int i = 2; i <= val; i++) {
            f = f.multiply(BigInteger.valueOf(i));
        }

        return f;
    }

    // Driver method
    public static void main(String[] args) {
        int val = 25;
        System.out.println(calculateFactorial(val));
    }
}

Output

15511210043330985984000000

Explanation

In the snippet above, the factor of a large number is calculated using BigInteger Class by importing java.math.BigInteger package. We have created a calculateFactorial method. This method creates a BigInteger and then calculates the factorial by using the multiply method f.multiply(BigInteger.valueOf(i)).

Example 2


import java.math.BigInteger;
public class Example2 {

    public static void main(String[] args) {
        BigInteger big1 = new BigInteger("20");
        BigInteger big2 = new BigInteger("60");
        BigInteger sub = big2.subtract(big1);
        System.out.println(big2 + " - " + big1 + " = " + sub);
        BigInteger add = big1.add(big2);
        System.out.println(big1 + " + " + big2 + " = " + add);
        BigInteger mul = big1.multiply(big2);
        System.out.println(big1 + " * " + big2 + " = " + mul);
        BigInteger div = big2.divide(big1);
        System.out.println(big2 + " / " + big1 + " = " + div);
        BigInteger min = big1.min(big2);
        System.out.println("min value: " + min);
        BigInteger max = big1.max(big2);
        System.out.println("max value: " + max);
    }
}

Output

60 - 20 = 40 60 + 20 = 80 60 * 20 = 1200 60 / 20 = 3 min value: 20 max value: 60

Explanation

In the snippet above, we have made two BigIntegers using the BigInteger(String val) constructor. We applied different methods on the BigIntegers big1 and big2 with the values 20 and 60 respectively. We applied the following methods:
  1. big2.subtract(big1) to subtract 20 from 60.
  2. big1.add(big2) to add 20 and 60.
  3. big1.multiply(big2) to multiply 20 and 60.
  4. big2.divide(big1) to divide 60 by 20.
  5. big1.min(big2) to get the smaller of the two values.
  6. big1.max(big2) to get the larger of the two values.
It is important to note that java.math.BigInteger is imported at the top of the code.

Conclusion

By now you should be familiar with the BigInteger Class in Java. You should be able to use BigIntegers in your code using different types of constructors. You should also be able to perform different arithmetic and logical operations on them by using BigInteger Class methods. As a challenge, you can try calling different methods with different values of BigIntegers. It will further strengthen your understanding of BigIntegers in Java. To be more confident in your learning try practicing it over and over. The key to good coding is practice. Best of luck and happy coding!
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION