I'm starting my studies in Java and I have a task: generate two random integers and store their multiplication. For that, I tried using
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);
getN() method generates and returns a random value.
Output example for
n , respectively:
1274403499 1155563989 -664855737
(As I understand it, it should be
1472654790899997511 , which uses something around 61 bits)
It's simple, the code is multiplying two integers and passing it to a method that will create a
BigInteger . When the multiplication of two integers takes place, it overflows and gives the negative value.
Probably the expectation was that the integers were passed to
BigInteger number and then multiplied. It solves like this:
int p = 1274403499; int q = 1155563989; BigInteger n1 = BigInteger.valueOf(p); BigInteger n2 = BigInteger.valueOf(q); BigInteger n = n1.multiply(n2);
See working on ideone . And on repl.it. Also posted on GitHub for future reference .