-2

I have trouble with detecting overflow. I am supposed to make a program that reads an int c , then int n pairs of numbers which should be multiplied.After the numbers are multiplied you need to check if it's integer overflow or not.If it's not overflow print the numbers multiplied.

In c++;

Here is an example :

Enter: 3 2147483647 and 2147483647

18446744073709551615 and 2

666013 and 1

Outputs:

4611686014132420609

Overflow!

666013


fin>>c;
for (i=1;i<=c;i++,p=0){
    fin>>a>>b;
    p=a*b;
    if (p/b==a)
        fout<<p<<"\n";
    else
        fout<<"Overflow"<<"\n";
}




return 0;
}
Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
  • 1
    What have you done so far? Due to the wording, your assignment appears to be a trick. Even if you check for overflow *after* the operation, you cannot use the result to check it. You can only check it using the operands. – eerorika Jan 07 '16 at 16:27
  • Don't post code in comments. Put your code in your question. Also describe how your code behaves and how you expect it to behave.. – eerorika Jan 07 '16 at 16:30
  • It doesn't matter where i check for overflow as long as the result is good – Theâ Razvan Jan 07 '16 at 16:34

1 Answers1

1

You've fallen into the trap of trying to use the result to test whether there was an overflow. You can't in fact do that. Signed integer overflow has undefined behaviour, so once it has happened, you're already screwed. You must check for overlow using the operands, before the operation.

Let max be the maximum representable integer. Assuming the operands are positive, a * b overflows if and only if a * b > max. But you cannot perform that test because if a * b overflows, the result is unusable. Besides, we know that no integer is bigger than max, so that test would always be false.

So, how can we use the equation, without using the result of a * b? We shall use the magic of maths and we end up with an equivalent equation: a > max / b. We only use the integer division operator, which does not overflow, Nice! Now, the equivalence of the equations only holds when b != 0. Trying to divide max / 0 would be an error. But, we know that a * 0 does not overflow for any a, so we can trivially implement that special case.

So, what we have is:

int a, b;
// don't forget to initialize
if(b && a > INT_MAX / b)
    // overflow, abort!
else
    // no overflow, proceed

This only works correctly for positive inputs. I'll leave it as an exercise to the reader to implement the test for all integers.

eerorika
  • 232,697
  • 12
  • 197
  • 326