-3

I am trying to solve this one particular problem involving basic math. My algorithm works for every other test cases and thus i know its correct. But for one particular input in one of the test cases, the result is wrong. I checked the values by printing them and values are:

a = 1000000000 and b = 999999999

When I do

System.out.print(a*b); 

it returns 1808348672.

I have tried doing this:

long ans = (long)a*b;
System.out.print(ans);

It still returns 1808348672

user207421
  • 305,947
  • 44
  • 307
  • 483
  • 1
    That’s a bad duplicate — it doesn’t answer this question. The real issue is that the problem isn’t reproducible because OP’s code works. – Konrad Rudolph Sep 07 '20 at 07:35
  • @Mureinik Please leave it alone. The whole problem here is that there was *no* relevant [tag:casting]. Just a non-reproducible problem. – user207421 Sep 08 '20 at 10:28

2 Answers2

5

I have tried doing this:

long ans = (long)a*b;
System.out.print(ans);

It still returns 1808348672

No, it doesn’t:

class Foo {
    public static void main(String[] args) {
        int a = 1000000000;
        int b = 999999999;
        long ans = (long)a*b;
        System.out.print(ans);
    }
}
javac foo.java && java Foo
999999999000000000

What you probably tried instead is

long ans = (long) (a*b);

This will first perform integer multiplication, and then cast the result to long. That doesn’t work since the integer multiplication overflows before your cast happens.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
2

a and b are ints, so their multiplication will also be an int, which overflows before being promoted to a long by the explicit cast.

You can define them as longs or cast them individually to longs before performing the multiplication.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • It worked by casting each of them individually. But why do I need to cast them individually? I tried to cast the whole operation and it didn't work. – Jaideep Kular Sep 07 '20 at 07:40
  • 1
    @JaideepKular casting the result is too late - multiplying two `int` will result in an `int`, which already overflows before you cast it. If you cast them individually, you'd be multiplying two `long`s, which result in a `long` that can accommodate the result without overflowing. – Mureinik Sep 07 '20 at 07:53