Logo

Programming-Idioms

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

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.

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.
public bool WillOverwflow(int x, int y) => int.MaxValue / x < y;

New implementation...
< >
deleplace