Logo

Programming-Idioms

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

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.

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;
}
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;
}

New implementation...
< >
deleplace