Logo

Programming-Idioms

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

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.

static boolean multiplyWillOverflow(int x, int y) {
	return Integer.MAX_VALUE/x < y;
}
public bool WillOverwflow(int x, int y) => int.MaxValue / x < y;
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;
}
import core.checkedint;
bool multiplyWillOverflow(int x, int y)
{
    bool result;
    core.checkedint.muls(x, y, result);
    return result;
}
logical function multiply_will_overflow (x, y) result(res)
    integer, intent(in) :: x, y
    integer, parameter :: ik = selected_int_kind (int(digits(y)*log10(2.)*2))

    res = int(x,kind=ik) * int(y,kind=ik) > huge(x)
end function multiply_will_overflow
func multiplyWillOverflow(x, y uint64) bool {
   if x <= 1 || y <= 1 {
     return false
   }
   d := x * y
   return d/y != x
}
function multiplyWillOverflow($x, $y)
{
      return ($x * $y) > PHP_INT_MAX;
}
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; 
sub multiply_will_overflow {
    my ($x, $y) = @_;
    return 'Inf' eq $x * $y;
}
def multiplyWillOverflow(x,y):
	return False
def multiplyWillOverflow(x,y)
  false
end
fn multiply_will_overflow(x: i64, y: i64) -> bool {
    x.checked_mul(y).is_none()
}

New implementation...
< >
deleplace