Logo

Programming-Idioms

History of Idiom 86 > diff from v5 to v6

Edit summary for version 6 by :
New Pascal implementation by user [Bart]

Version 5

2015-11-30, 12:37:31

Version 6

2016-02-07, 16:58:03

Idiom #86 Check if integer multiplication will overflow

Write boolean function multiplyWillOverflow which takes two integers x, y and return true if (x*y) overflows.

Idiom #86 Check if integer multiplication will overflow

Write boolean function multiplyWillOverflow which takes two integers x, y and return true if (x*y) overflows.

Code
function MultiplyWillOverflow(x, y: Integer): Boolean;
begin
  if ((x and y) = 0) then
    Result := False
  else
  begin
    if ((x > 0) and (y > 0)) or ((x < 0) and (y < 0)) then
      Result := ((High(Integer) div Abs(x)) > Abs(y))
    else
      Result := Abs(Low(Integer) div Abs(x)) > Abs(y);
  end;
end; 
Comments bubble
Thee is a separate branch for the case where x and y differ in sign, since Low(Integer) is not the same as -High(Integer).