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

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.

  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
public bool WillOverwflow(int x, int y) => int.MaxValue / x < y;
import core.checkedint;
bool multiplyWillOverflow(int x, int y)
{
    bool result;
    core.checkedint.muls(x, y, result);
    return result;
}
func multiplyWillOverflow(x, y uint64) bool {
   if x <= 1 || y <= 1 {
     return false
   }
   d := x * y
   return d/y != x
}
static boolean multiplyWillOverflow(int x, int y) {
	return Integer.MAX_VALUE/x < y;
}
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()
}

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

deleplace

Related idioms