Overflow by multiplying two integers in BigInteger

Posted on

Question :

I’m starting Java studies and I have one task: to generate two random integers and store their multiplication. For this, I tried to use long and BigInteger . But the result of this multiplication is almost always negative. Why?

int p = a.getN();
int q = b.getN();
BigInteger n = BigInteger.valueOf(p * q);

The getN() method generates and returns a random value.

Example output for p , q and n , respectively:


(so I understand, it should be 1472654790899997511 , which uses something around 61 bits)


Answer :

It’s simple, the code is multiplied by two integers and passing to a method that will create a BigInteger . When the multiplication of two integers occurs, there is overflow and gives the negative value.

Probably the expectation was that the integers were passed to number BigInteger and then multiplied. Resolves like this:

int p = 1274403499;
int q = 1155563989;
BigInteger n1 = BigInteger.valueOf(p);
BigInteger n2 = BigInteger.valueOf(q);
BigInteger n = n1.multiply(n2);

See running on ideone .


Leave a Reply

Your email address will not be published. Required fields are marked *