Programming-Idioms

History of Idiom 86 > diff from v14 to v15

Edit summary for version 15 :
[Go] Variables names and func name

Version 14

2017-04-13, 15:25:21

Version 15

2017-04-13, 15:26:34

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.

Code
func mulOverflows(a, b uint64) bool {
   if a <= 1 || b <= 1 {
     return false
   }
   c := a * b
   return c/b != a
}
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
Origin
http://grokbase.com/p/gg/golang-nuts/148wvnxk76/go-nuts-re-test-for-an-integer-overflow