Overflow by multiplying two integers in Biginteger

Asked

Viewed 368 times

4

I am starting studies in Java and have a task: 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 method getN() generates and returns a random value.

Output example for p, q and n, respectively:

1274403499
1155563989
-664855737

(from what I understand, it should be 1472654790899997511, that uses something around 61 bits)

1 answer

7


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

Probably the expectation was that the integers were passed on to number BigInteger and then, yes, multiplied. Solve like this:

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

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • only need to tidy the line 4: Biginteger N2 = Biginteger.valueOf(q);, is doing p 2. But the idea is correct and I managed to apply. Thank you :-)

  • It’s true @eightShirt. Tidy.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.