Home > database >  Multiplication overflow problem in int and long in java
Multiplication overflow problem in int and long in java

Time:01-16

Multiplication of 123456789 and 987654321 is yielding in -67153019. I have used both int and long types but couldn't find the required result.

int n1 = 123456789 ;
int n2 = 987654321 ;
long ans = n1*n2 ;

The result should be 121932631112635269 but it comes out to be -67153019.

CodePudding user response:

This is because 121932631112635269 is greater than max int, so when doing n1 * n2, the result parsed to int will be garbage. The cast to Long is made after the math, when it tries to do the = with ans.

If you cast n1 and n2 to long before, doing the math you will get 121932631112635269.

    int n1 = 123456789 ;
    int n2 = 987654321 ;
    long ans = (long)n1 * (long)n2;

or like this:

    int n1 = 123456789 ;
    int n2 = 987654321 ;
    long ans = 1L * n1 * n2;

or if you change n1 and n2 types to long

edit: as Turing85 says,

the 2nd cast is superfluous

since the n1 would be cast to long before, there's no need to cast n2, since the result would be a Long. Making:

int n1 = 123456789 ;
int n2 = 987654321 ;
long ans = (long)n1 * n2;

also correct

CodePudding user response:

It is due to order of operations. In your case, first JVM tries to multiply 2 ints as an int (because result of binary operation with int operands is also an int), and only then puts the result to long because the left-hand side variable has long type.

Please try this:

long ans = 1L * n1 * n2;

This should solve the overflow issue.

  • Related