Skip to content

Instantly share code, notes, and snippets.

@as
Last active January 25, 2019 12:55
Show Gist options
  • Save as/a6a5bef58456abc3e6dcadd95431c07a to your computer and use it in GitHub Desktop.
Save as/a6a5bef58456abc3e6dcadd95431c07a to your computer and use it in GitHub Desktop.
binary greatest common divisor
package main
import (
"fmt"
"math/bits"
)
func main() {
fmt.Println(bgcd(6, 36))
fmt.Println(bgcd(2, 36))
fmt.Println(bgcd(3, 9))
fmt.Println(bgcd(3, 5))
}
func ctz(u uint32) uint32 {
return uint32(bits.TrailingZeros32(u))
}
func ctz(u uint32) uint32 {
return uint32(bits.TrailingZeros32(u))
}
func bgcd(a, b uint32) uint32 {
if a == 0 || b == 0 {
return a | b
}
s := ctz(a | b)
for ; b > 0; b -= a {
a >>= ctz(a)
b >>= ctz(b)
if a > b {
a, b = b, a
}
}
return a << s
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment