Skip to content

Instantly share code, notes, and snippets.

@areed
Last active August 29, 2015 14:05
Show Gist options
  • Save areed/85d3614a58400e417027 to your computer and use it in GitHub Desktop.
Save areed/85d3614a58400e417027 to your computer and use it in GitHub Desktop.
Rob Pike's integer multiplication overflow tests from golang-nuts mailing list
func mulOverflows(a, b uint64) bool {
if a <= 1 || b <= 1 {
return false
}
c := a * b
return c/b != a
}
const mostNegative = -(mostPositive + 1)
const mostPositive = 1<<63 - 1
func signedMulOverflows(a, b int64) bool {
if a == 0 || b == 0 || a == 1 || b == 1 {
return false
}
if a == mostNegative || b == mostNegative {
return true
}
c := a * b
return c/b != a
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment