Logo

Programming-Idioms

  • Java
  • Php

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)
{
      return ($x * $y) > PHP_INT_MAX;
}

PHP_INT_MAX has different values on 32bit vs 64bit machines.

PROBLEM: this works only when $x and $y are positive.
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.
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