Logo

Programming-Idioms

History of Idiom 86 > diff from v22 to v23

Edit summary for version 23 by programming-idioms.org:
[Go] Dead link

Version 22

2019-10-08, 14:34:49

Version 23

2020-05-21, 20:16:53

Idiom #86 Check if integer multiplication will overflow

Write boolean function multiplyWillOverflow which takes two integers x, y and return true if (x*y) overflows.

Idiom #86 Check if integer multiplication will overflow

Write boolean function multiplyWillOverflow which takes two integers x, y and return true if (x*y) overflows.

Variables
multiplyWillOverflow,x,y
Code
func multiplyWillOverflow(x, y uint64) bool {
   if x <= 1 || y <= 1 {
     return false
   }
   d := x * y
   return d/y != x
}
Code
func multiplyWillOverflow(x, y uint64) bool {
   if x <= 1 || y <= 1 {
     return false
   }
   d := x * y
   return d/y != x
}
Comments bubble
This holds for uint64, not for signed integers.
Note that the multiplication is performed, then its result is checked.
Comments bubble
This holds for uint64, not for signed integers.
Note that the multiplication is performed, then its result is checked.
Origin
http://grokbase.com/p/gg/golang-nuts/148wvnxk76/go-nuts-re-test-for-an-integer-overflow