# BigInteger Class in Java

Java contains built-in or primitive data that deals with the type and size a variable can take in order to perform mathematical operations. But, sometimes, they are not capable enough to hold calculated values as they have some limitations.

For example, a long data type can have values ranging from -263 to 263-1, capable of holding the highest value among primitive data types.

Let’s say you have to calculate a factorial of 200 that will give you 375 digits or mass of the earth, which weigh around 5.972 × 1024 kg, beyond the range of the value a primitive data type can hold.

Java BigInteger class deals with the very big integers, empowering you to store as big integer values you want; theoretically, there is no limit. However, it is limited pragmatically due to the limited memory of a system.

In this guide, we will consider every single factor around BigInteger Class in Java so that you can understand the topic easily.

## What is BigInteger Class in Java?

BigInteger is a class library that is built to handle calculations involving very large integers. It is designed to handle calculations that a normal primitive integer data type cannot handle.

Java BigInteger class implements a comparable interface and extends the Number class. JavaBigInteger class can perform all the functionalities such as addition, subtraction, product, division, and finding GCD of two numbers.

## Methods to Initialize BigInteger Class in Java?

There are various ways through which we can initialize the variables of BigInteger data type.

Following are few methods to do the same:

1. BigInteger(byte[] value): By this constructor, an array of bytes storing 2’s complement binary encoded integer is passed as an argument.
2. BigInteger(int sign of Number, byte[] magnitudeOfNumber): Using this constructor, we can initialize the variable bypassing the sign along with the magnitude of the integer.
3. BigInteger(int numberBits, Random value): Used to generate a random number that may be in the range of zero to power(2, numberBits) - 1 inclusively.
4. BigInteger(String value): An integer variable can be initialized by passing a string form of the integer using this constructor.

## How to Declare BigInteger Class in Java?

Like the normal integer data type, we can declare the variables of BigInteger data type in the same way.

Following is the comparative way in which we can declare integer as well as BigInteger data type variables:

``````int var1, var2;
BigInteger VAR1, VAR2;``````

From the above example, we can see that we have declared the variables of BigInteger data type in all caps; it’s considered good practice to do so because they are instances of BigInteger class. Thus, to differentiate it with integer data types variables types, we do so.

``````var1 = 54;
var2 = 23;
VAR1  = BigInteger.valueVAR1  = new BigInteger("504");
VAR2  = new BigInteger("3572435378609854313");``````

For initializing variable by passing a string as an argument:

``````VAR1  = new BigInteger("504");
VAR2  = new BigInteger("3572435378609854313"); ``````

For performing a small arithmetic operation:

``````int res = var1 + var2;

## Methods offered by Java BigInteger class

S.NO Method Name Description
1. BigInteger abs() This method returns a positive (absolute) value of BigInteger data type.
2. BigInteger add(BigInteger value) Returns a new BigInteger with resulting value equal to calling object value-added with passed object's value.
3. BigInteger and(BigInteger value) Returns a new BigInteger with resulting value equal to calling object value bitwise AND (&) with passed object's value.
4. BigInteger andNot(BigInteger value) Returns a new BigInteger with resulting value equal to calling object value bitwise AND (&) with negated passed object's value.
5. int bitCount() Returning the number of bits in this BigInteger's two's complement representation that differ from its sign bit.
6. int bitLength() Returning the count of bits in minimal 2's complement form (not including the sign bit).
7. BigInteger clearBit(int n) Returning a BigInteger after clearing its designated bits from original representation.
8. int compareTo(BigInteger value) Compares the calling object's value with that of the value passed in the argument.
9. BigInteger divide(BigInteger value) Returns a new BigInteger with resulting value equal to calling object value divided with passed object's value.
10. BigInteger[ ] divideAndRemainder(BigInteger value) Returns two new BigInteger arrays with one containing resulting value equal to calling object value divided with passed object's value and the other containing resulting value of 9objectValue%value).
11. double doubleValue() Return the double value after converting the BigInteger value into double.
12. boolean equals(Object x) Compares the passed object value with that of calling the object's value.
13. BigInteger flipBit(int n) Returns a new BigInteger with a value obtained after flipping the designated bit.
14. float floatValue() Returns the float equivalent value of the big integer object.
15. BigInteger gcd(BigInteger value) Returns the greatest common divisor of the two (calling object's value and abs(value)).
16. int getLowestSetBit() Returns the index of the lowest set bit, i.e., the bit with value = 1, in the calling object's value.
17. int hashCode() This method returns the hashcode for the calling BigInteger object's value.
18. int intValue() Returns the value after converting the BigInteger object's value into integer datatype.
19. boolean isProbablePrime(int num) Does the primality test and returns true, if the number is prime, else returns false.
20. long longValue() Returns the value after converting the BigInteger object's value into a long long data type.
21. BigInteger max(BigInteger value) Returns the value that is maximum among the both (calling object's value or value).
22. BigInteger min(BigInteger val) Returns the value that is minimum among the both (calling object's value or value).
23. BigInteger mod(BigInteger number) Returning a value which is equal tob(calling object's value)mod (number).
24. BigInteger modInverse(BigInteger m) Returning a value that is equal to the inverse of (calling object's value)mod (number).
25. BigInteger modPow(BigInteger exp, BigInteger modulo) Returns the value which is equal to (object's value raised to power exp) mod modulo.
26. BigInteger multiply(BigInteger value) Returns a new BigInteger with resulting value equal to calling object value multiplied with passed object's value.
27. BigInteger negate() Returns the negated value of the calling object's value.
28. BigInteger nextProbablePrime() Returns the prime number which is just greater than the calling object's value.
29. BigInteger not() Returns the ~this value for the calling object.
30. BigInteger or(BigInteger value) Returns a new BigInteger with resulting value equal to calling object value bitwise OR with passed object's value.
31. BigInteger pow(int exp) Returns the value which is equal to calling object's value multiplied exp times with each other.
32. static BigInteger probablePrime(int bitLen, Random rand) Returns the nonnegative BigInteger which will be a prime number of length bitLen.
33. BigInteger remainder(BigInteger val) Returns the value after performing the modulo operation with Val.
34. BigInteger setBit(int n) Returns a new BigInteger after setting the nth indexed = 1.
35. BigInteger shiftLeft(int num) Returns a number after shifting the calling object's value num times to the left.
36. BigInteger shiftRight(int num) Returns a number after shifting the calling object's value num times to the right.
37. int signum() Returns -1, 0, or 1 based on the sign of the calling object's value.
38. BigInteger subtract(BigInteger value) Returns a new BigInteger with resulting value equal to calling object value to subtract with passed object's value.
39. boolean testBit(int num) Returns true if the nth index bit is set in calling object's value.
40. byte[] toByteArray() Returning an array containing 2’s complement of calling object's bigInteger.
41. String toString() Converts the decimal to string representation.
42. String toString(int radix) Converts the decimal form into string format for the specified radix.
43. static BigInteger valueOf(long val) Returns a BigInteger containing value equivalent to passed long value as parameter.
44. BigInteger xor(BigInteger val) Returns a new BigInteger with a resulting value equal to (calling object value) XOR (passed object's value).

Code example

``````import java.math.BigInteger;
public class Main
{
public static void main(String args[])  {
// Initializing result variable
BigInteger var1 = new BigInteger("110");
//returns the output of string to integer
BigInteger var2= new BigInteger("171");
System.out.println("Signum value for "+ var2 +" : "+ var2.signum());
//returns the next prime integer that is greater than this BigInteger.
BigInteger substract=var2.subtract(var1);
System.out.println(var2+"-"+var1+" : "+substract);

// calculates quotient after performing division of 2 values
BigInteger quot = var2.divide(var1);
System.out.print(var2 + " / " + var1+" :     Quotient : "+quot);

//calculate remainder after performing division of 2 values
BigInteger remainder=var1.remainder(var2);
System.out.println("\nRemaider : "+remainder);

//returns a BigInteger whose value is ?this << val?
BigInteger leftShift = var1.shiftLeft(3);
System.out.println("Value after performing left shift : "+ leftShift );
BigInteger rightShift = var1.shiftRight(3);
System.out.println("Value after performing right shift : "+ rightShift);
}
} ``````

Output:

``````Signum value for 171 : 1
171-110 : 61
171 / 110 :     Quotient : 1
Remainder : 110
Value after performing left shift : 880
Value after performing right shift : 13``````

In the above code, we have performed string to int conversion function, subtract function, divide function, etc. So the syntax for calling every method remains the same, i.e., using the dot (.) operator.

This is because Java is an object-oriented language. So, each declared variable is an object of respective data types. Hence, the dot operator has to be used to call any member function of that class.

There are various methods to construct a BigInteger in a Java program in order to use it throughout the program, performing mathematical operations.

1. Through primitive data types
2. Passing a string within a constructor
3. Initialization from a file

The following program will help you to elucidate the operation of Big Integers:

``````import java.math.BigInteger;
import java.util.Scanner;

public class Main{
public static void main(String[] args){
//constructing a BigInteger through constructor
BigInteger a = new BigInteger("value"); //method 1

BigInteger b = BigInteger.valueOf(268985); //method 2
BigInteger c= BigInteger.TEN ; //using constant values

//Performing the basic mathematical operations

BigInteger result2= a.multiply(c) ;//multiplication
BigInteger result3= c.subtract(a) ; //subtraction
BigInteger result4= b.divide(c); //division

//print the results
System.out.println("" + result1 + result2 + result3 + result4);

BigInteger immute = new BigInteger ("111");
immute.multiply(new BigInteger ("210"));
//Print the result

System.out.println(immute); //result: 111
/*In java , objects of immutable class cannot be changed once they are declared. By default, string and wrapper classes are immutable */

//Mod operations
BigInteger mod1, mod2; //creating BigInteger objects
mod1 = new BigInteger("500");
mod2 = new BigInteger ("220");
//Perform the modulus

BigInteger ModResult = mod1.mod(mod2);
//Print result

System.out.println(ModResult.toString()); //output: 60

//Performing inverse mod
BigInteger InverseMod = mod1.modInverse(mod2);
//print result
System.out.println(InverseMod.toString()); //Output:

}
}``````

### Conclusion

Throughout this article, we have gone through the introduction of the Java BigInteger class. We have seen various inbuilt methods offered by it. We compared the syntax of BigInteger class with that of primitive data types.

However, BigInteger class internal implementation is based on arrays to affect the whole algorithm's overtime complexity.

Recommended Posts: