Last active
January 7, 2025 23:44
-
-
Save koonix/b2067fe699ec87be44a1081f22235773 to your computer and use it in GitHub Desktop.
Go 64-bit multiplication and division without overflow.
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
import "math/bits" | |
func mulDiv(a, b, c int64) int64 { | |
hi, lo := bits.Mul64(uint64(a), uint64(b)) | |
quo, _ := bits.Div64(hi, lo, uint64(c)) | |
return int64(quo) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment