Logo

Programming-Idioms

History of Idiom 86 > diff from v8 to v9

Edit summary for version 9 by :
New Go implementation by user [Logiraptor]

Version 8

2016-02-17, 04:20:32

Version 9

2016-02-18, 16:58:02

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; 
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
There is a separate branch for the case where x and y differ in sign, since Low(Integer) is not the same as -High(Integer).
Comments bubble
There is a separate branch for the case where x and y differ in sign, since Low(Integer) is not the same as -High(Integer).