Logo

Programming-Idioms

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

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.

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

The only standard way to do this in Fortran, without invoking undefined behavior, is to perform the multiplication with integer type that can hold the result and check for the overflow.
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