Logo

Programming-Idioms

  • Java
  • Python
  • Go
  • Rust

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.

boolean b = Math.multiplyExact(x, y);
static boolean multiplyWillOverflow(int x, int y) {
	return Integer.MAX_VALUE/x < y;
}

PROBLEM: this works only when x and y are positive.
def multiplyWillOverflow(x,y):
	return False

Python has arbitrary precision integers so you shouldn't worry about overflow.
Also, don't bother coding this constant function!
func multiplyWillOverflow(x, y uint64) bool {
   if x <= 1 || y <= 1 {
     return false
   }
   d := x * y
   return d/y != x
}

This holds for uint64, not for signed integers.
Note that the multiplication is performed, then its result is checked.
fn multiply_will_overflow(x: i64, y: i64) -> bool {
    x.checked_mul(y).is_none()
}

checked_mul is available on all integer types
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