c++ - Checking multiple numbers for overflow -


i have trouble detecting overflow. supposed make program reads int c , int n pairs of numbers should multiplied.after numbers multiplied need check if it's integer overflow or not.if it's not overflow print numbers multiplied.

in c++;

here example :

enter: 3 2147483647 , 2147483647

18446744073709551615 , 2

666013 , 1

outputs:

4611686014132420609  overflow!  666013   fin>>c; (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; } 

you've fallen trap of trying use result test whether there overflow. can't in fact that. signed integer overflow has undefined behaviour, once has happened, you're screwed. must check overlow using operands, before operation.

let max maximum representable integer. assuming operands positive, a * b overflows if , if a * b > max. cannot perform test because if a * b overflows, result unusable. besides, know no integer bigger max, test false.

so, how can use equation, without using result of a * b? shall use magic of maths , end equivalent equation: a > max / b. use integer division operator, not overflow, nice! now, equivalence of equations holds when b != 0. trying divide max / 0 error. but, know a * 0 not overflow a, can trivially implement special case.

so, have is:

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

this works correctly positive inputs. i'll leave exercise reader implement test integers.


Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -