Java - BigInteger Handling Large Numbers

ZoneTechPro
By -
0

 

BigIntegers


Java biginteger handling large numbers
Java - Biginteger



Introduction

We have learned about various data types such as int, long, etc in Java in the previous unit. By using these data types, we can hold numbers of varying ranges. For instance int (-231 to 231-1), long (-263 to 263-1), etc.


In actual applications, we can obtain use cases where we require storing large integers which int and long data types are not able to store. For instance, the factorial of 21 is 51090942171709440000, which is too large for an int or long type to hold.


Example

class Main {

    public static void main(String[] args) {

        long num = 51090942171709440000L;

System.out.println(num);

}

}


Output:


file.java:3: error: integer number too large

        long num = 51090942171709440000L;


In the above example, the value of num is larger than 263-1 (range of long data type). So it causes an error.



How to store large numbers in Java?


Java has a class named BigInteger to store large numbers.


Let's know how to store big integers through the BigInteger class and do various operations on them.


1. BigInteger


BigInteger is the class employed for the mathematical operations involving extremely large integer calculations beyond the range of all available primitive types.


Declaration of a BigInteger

To declare the BigInteger variables, we have to import the BigInteger class from the java.math package.


Syntax:


BigInteger bigNum;


Here,


BigInteger: is the class name.

bigNum: it is the name of the variable BigInteger.



Code


import java.math.BigInteger;


class Main {

    public static void main(String[] args) {

        BigInteger bigNum; // declaring bigNum as variable BigInteger

    }

}


Initialization

To make a BigInteger variable initialized, we can use the new keyword.


Syntax


BigInteger bigNum = new BigInteger(str);


Here,


bigNum: it is the variable name

str: is the argument value to be passed. It must be of string data type.



Code


import java.math.BigInteger;


class Main {

    public static void main(String[] args) {

        String str = "51090942171709440000";

        BigInteger bigNum = new BigInteger(str);     // declaring bigNum as BigInteger variable and                                                                                              initializing it.

        System.out.println(bigNum);

}

}


Output

51090942171709440000



2. BigInteger Methods


In Java, arithmetic operators (+, -, *, /) cannot be used with BigIntegers, we must use methods of BigInteger class to perform these arithmetic operations.


An important feature of BigIntegers is also the fact that they are immutable. This is to say that you can't alter the stored value of a BigInteger object, rather you must assign the altered value to a new variable.


Let's see some of the methods of BigInteger.


Addition

The add() method adds the given two BigIntegers and returns the result.


Syntax


bigNum1.add(bigNum2);

Here, bigNum1 and bigNum2 must be BigIntegers.


Code


import java.math.BigInteger;


class Main {

    public static void main(String[] args) {

        BigInteger bigNum1 = new BigInteger("51090942171709440000");

        BigInteger bigNum2 = new BigInteger("2432902008176640000");

        BigInteger sum = bigNum1.add(bigNum2);

        System.out.println("Sum of the BigIntegers = " + sum);

        System.out.println("bigNum1 = " + bigNum1);

        System.out.println("bigNum2 = " + bigNum2);

    }

}


Output:


Sum of the BigIntegers = 53523844179886080000

bigNum1 = 51090942171709440000

bigNum2 = 2432902008176640000


As we have already studied, the BigIntegers are immutable.


From the above code we can observe that the BigIntegers are not being modified, the add() function returned a new BigInteger which is stored in another BigInteger named as sum.


Subtraction

The subtract() function subtracts the given two BigIntegers and returns the difference.


Syntax


bigNum1.subtract(bigNum2);

Here, bigNum1 and bigNum2 must be BigIntegers.


Code


import java.math.BigInteger;


class Main {

    public static void main(String[] args) {

BigInteger bigNum1 = new BigInteger("51090942171709440000");

        BigInteger bigNum2 = new BigInteger("2432902008176640000");


        BigInteger difference = bigNum1.subtract(bigNum2);


        System.out.println(difference);

    }

}


Output:


48658040163532800000


Multiplication

The multiply() method does the multiplication of the given two BigIntegers and returns the result.


Syntax

bigNum1.multiply(bigNum2);

Here, bigNum1 and bigNum2 must be BigIntegers.


Code


import java.math.BigInteger;


class Main {

    public static void main(String[] args) {

        BigInteger bigNum1 = new BigInteger("51090942171709440000");

        BigInteger bigNum2 = new BigInteger("2432902008176640000");

        BigInteger product = bigNum1.multiply(bigNum2);

        System.out.println(product);

    }

}


Output:


124299255809188481393766275481600000


Division

The divide() method does the division of the specified two BigIntegers and returns the quotient.


Syntax

bigNum1.divide(bigNum2);

Here, bigNum1 and bigNum2 must be BigIntegers.


Code:


import java.math.BigInteger;

class Main {

    public static void main(String[] args) {

        BigInteger bigNum1 = new BigInteger("124299255809188481393766275481600000000");

        BigInteger bigNum2 = new BigInteger("2432902008176640000");

        BigInteger quotient = bigNum1.divide(bigNum2);

System.out.println(quotient);

   }

   }


Output:


51090942171709440000


Exponentiation

The pow() function calculates the exponentiation for the specified BigInteger

It returns the bigNumexponent result


Syntax


bigNum.pow(exponent);

Where,

bigNum: must be a BigInteger


exponent: must be of int data type, exponent must be 0 or a positive number. If the exponent is negative, then an error would be thrown.


Code


import java.math.BigInteger;


class Main {

public static void main(String[] args) {

        BigInteger bigNum = new BigInteger("632");

        int exp = 16;

        BigInteger power = bigNum.pow(exp); // result as (num)^exp


        System.out.println(power);

    }

}


Output:


6478481941368253313898664181301119442233


Absolute value


The abs() function returns a BigInteger type value which is equal to the absolute value of the specified BigInteger.


An absolute value of a number is a positive value (it is always non-negative). For instance, the absolute value of -3 is 3, and the absolute value of 3 is 3 as well.


Syntax


bigNum.abs();

Here, bigNum must be a BigInteger.


Code


import java.math.BigInteger;


class Main {

    public static void main(String[] args) {

        BigInteger bigNum1 = new BigInteger("2345678910");

        BigInteger bigNum2 = new BigInteger("-8465931324");

        BigInteger absValue1 = bigNum1.abs();

        BigInteger absValue2 = bigNum2.abs();

System.out.println(absValue1);

System.out.println(absValue2);

    }

}


Output:


2345678910

8465931324


3. Type Conversions with BigIntegers

Converting Integers to BigInteger:


The valueOf() method can also be used to convert int or long values representing integers to a BigInteger. It takes a single argument and returns a BigInteger.

We will discuss Type Conversions later in the course.

The syntax for initializing a BigInteger variable with the valueOf() method is below:


Syntax


BigInteger.valueOf(num);


num is the number to be converted as a BigInteger. It must be of long data type. When an int data type is passed, it will be converted automatically to long.


Code


import java.math.BigInteger;


class Main {

    public static void main(String[] args) {

        int num = 2022;

long longNum = 435468567463L;

        BigInteger bigNum1 = BigInteger.valueOf(num);

        BigInteger bigNum2 = BigInteger.valueOf(longNum);

        System.out.println(bigNum1);

        System.out.println(bigNum2);

    }

}


Output:

2022

435468567463



Converting BigInteger to Integers or String

We can cast BigInteger to int, long, and String data types through the following methods,


intValue()

longValue()

doubleValue()

floatValue()

toString()


For all other data types except String, while converting BigIntegers to other data types, we have to make sure that the number comes within the range of the respective data type (i.e., int, long, etc).


Converting BigInteger to int Type


We can utilize the intValue() method to convert a BigInteger to an int data type.


Syntax


bigNum.intValue();


Code:


import java.math.BigInteger;

class Main

public static void main(String[] args) {

        int num = 2022;

        BigInteger bigNum1 = BigInteger.valueOf(num);

        num = bigNum1.intValue();

        System.out.println(num);

    }


Output:


2022


In the code above, we can observe that the int value is first converted to BigInteger and then using the intValue() method the BigInteger is converted to int and the int value is assigned to the variable num.


We can also convert BigInteger to long, float, double, and String data type.


Let's consider the below example,


Code


import java.math.BigInteger;


public class Main {

    public static void main(String[] args) {

String str = "45900";

        BigInteger bigNum1 = new BigInteger(str);

        str = bigNum1.toString();

        long longNum = bigNum1.longValue();

        float floatNum = bigNum1.floatValue();

        double doubleNum = bigNum1.doubleValue();

        System.out.println(str);

        System.out.println(longNum);

        System.out.println(floatNum);

        System.out.println(doubleNum);

    }

}


Output:


45900

45900

45900.0

45900.0


4. BigInteger Constants


The BigInteger class provides some constants for the convenience of initialization.


BigInteger.ZERO: The BigInteger constant for 0

BigInteger.ONE: The BigInteger constant for 1

BigInteger.TWO: The BigInteger constant for 2

BigInteger.TEN: The BigInteger constant for 10


Let's see how to declare the BigInteger variables with BigInteger constants.


Code


import java.math.BigInteger;


class Main {

    public static void main(String[] args) {

        BigInteger bigNum0 = BigInteger.ZERO;

        BigInteger bigNum1 = BigInteger.ONE;

        BigInteger bigNum2 = BigInteger.TWO;

        BigInteger bigNum10 = BigInteger.TEN;

        System.out.println(bigNum0);

        System.out.println(bigNum1);

        System.out.println(bigNum2);

        System.out.println(bigNum10);

    }

}


Output:


0

1

2

10


These constant values can be used instead of using a constructor new BigInteger().

We do not need to define them. 


Summary

The valueOf() method takes a long value and converts it into a BigInteger value and returns it.


BigInteger Methods:


add(): It adds the given two BigIntegers and returns the addition.

subtract(): It subtracts the given two BigIntegers and returns the subtraction.

multiply(): It multiplies the given two BigIntegers and returns the product.

divide(): It divides the given two BigIntegers and returns the quotient.

pow(): It performs the exponentiation operation and returns the result.


Type Conversions with BigIntegers:


intValue(): It converts BigInteger to an int value and returns it.

longValue(): It converts BigInteger to a long value and returns it.

floatValue(): It converts BigInteger to a float value and returns it.

doubleValue(): It converts BigInteger to a double value and returns it.

toString(): It converts BigInteger to a String value and returns it.


BigInteger Constants:


BigInteger.ZERO: The BigInteger constant 0

BigInteger.ONE: The constant BigInteger 1

BigInteger.TWO: The constant BigInteger 2

BigInteger.TEN: The constant BigInteger 10

Tags:

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Learn more
Ok, Go it!