Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Pascal

Idiom #86 Check if integer multiplication will overflow

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

An overflow may reach above the max positive value, or below the min negative value.

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; 

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).
public bool multiplyWillOverflow(int x, int y) 
{
	if (x == 0)
		return false;

	if (y > int.MaxValue / x)
		return true;

	if (y < int.MinValue / x)
		return true;

	return false;
}

New implementation...
< >
deleplace