Skip to content

Instantly share code, notes, and snippets.

@anzdaddy
Created August 5, 2025 09:59
Show Gist options
  • Select an option

  • Save anzdaddy/d99be209edf11deb99d8d2a14e3404d5 to your computer and use it in GitHub Desktop.

Select an option

Save anzdaddy/d99be209edf11deb99d8d2a14e3404d5 to your computer and use it in GitHub Desktop.
div by const 10^16
func U128_div_10_16(hi, lo uint64) (q uint64) {
const d uint64 = 10_000_000_000_000_000
if hi == 0 {
return lo / d
}
const M = 557518629963265578538392957
const Mhi = M / (1 << 64)
const Mlo = M % (1 << 64)
lo = hi<<50 | lo>>14
hi >>= 14
b1, _ := bits.Mul64(lo, Mlo)
c2, b2 := bits.Mul64(hi, Mlo)
c3, b3 := bits.Mul64(lo, Mhi)
c4 := hi * Mhi
b, carry1 := bits.Add64(b1, b2, 0)
_, carry2 := bits.Add64(b, b3, 0)
return carry1 + carry2 + c2 + c3 + c4
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment