📜  java biginteger multiply - Java (1)

📅  最后修改于: 2023-12-03 14:42:13.374000             🧑  作者: Mango

Java BigInteger Multiply

Java BigInteger class can be used to perform arithmetic operations on very large numbers that cannot be handled by primitive data types. One such operation is multiplication. In this article, we will see how to use Java BigInteger class to multiply two large numbers.

Initializing BigInteger Objects

To use the BigInteger class, we need to initialize its objects. This can be done in various ways, such as:

Using a String Literal
BigInteger num1 = new BigInteger("12345678901234567890");
BigInteger num2 = new BigInteger("98765432109876543210");
Using a Long Literal
long l1 = 123456789012345678l;
long l2 = 987654321098765432l;

BigInteger num1 = BigInteger.valueOf(l1);
BigInteger num2 = BigInteger.valueOf(l2);
Using an Array of Bytes
byte[] b1 = new byte[] {0x01, 0x23, 0x45, 0x67, 0x89, 0x01, 0x23, 0x45, 0x67, 0x89};
byte[] b2 = new byte[] {0x98, 0x76, 0x54, 0x32, 0x10, 0x98, 0x76, 0x54, 0x32, 0x10};

BigInteger num1 = new BigInteger(b1);
BigInteger num2 = new BigInteger(b2);
Multiplying BigInteger Objects

Once we have initialized the BigInteger objects, we can use the multiply() method to multiply them. The multiply() method returns a new BigInteger object that contains the result of the multiplication.

BigInteger result = num1.multiply(num2);
Example Code
import java.math.BigInteger;

public class BigIntegerMultiply {
    public static void main(String[] args) {
        BigInteger num1 = new BigInteger("12345678901234567890");
        BigInteger num2 = new BigInteger("98765432109876543210");

        BigInteger result = num1.multiply(num2);

        System.out.println("Result: " + result);
    }
}
Conclusion

In this article, we saw how to use Java BigInteger class to multiply two large numbers. We also saw how to initialize BigInteger objects using various methods. The BigInteger class provides many other methods for performing arithmetic operations on very large numbers, which can be explored further.