Last active
August 29, 2015 14:05
-
-
Save areed/85d3614a58400e417027 to your computer and use it in GitHub Desktop.
Rob Pike's integer multiplication overflow tests from golang-nuts mailing list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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