2
0
mirror of https://github.com/0xAX/go-algorithms synced 2024-11-13 13:10:30 +00:00
go-algorithms/numerical/gcd.go

48 lines
581 B
Go
Raw Normal View History

2014-08-12 17:33:02 +00:00
package gcd
func gcd(x uint, y uint) uint {
2014-08-12 17:35:29 +00:00
var shift uint = 0
2014-08-12 17:33:02 +00:00
2014-08-12 17:35:29 +00:00
if x == y {
return x
}
2014-08-12 17:33:02 +00:00
2014-08-12 17:35:29 +00:00
if x == 0 {
return y
}
2014-08-12 17:33:02 +00:00
2014-08-12 17:35:29 +00:00
if y == 0 {
return x
}
2014-08-12 17:33:02 +00:00
2014-08-12 17:35:29 +00:00
for shift := 0; (x | y) & 1 == 0; shift++ {
x = x >> 1
y = y >> 1
}
2014-08-12 17:33:02 +00:00
2014-08-12 17:35:29 +00:00
for ; (x & 1) == 0 ; {
x = x >> 1
}
2014-08-12 17:33:02 +00:00
2014-08-12 17:35:29 +00:00
for ; y == 0 ; {
for ; (y & 1) == 0 ; {
y = y >> 1
}
2014-08-12 17:33:02 +00:00
2014-08-12 17:35:29 +00:00
if x > y {
t := x
x = y
y = t
}
2014-08-12 17:33:02 +00:00
2014-08-12 17:35:29 +00:00
y = y - x
2014-08-12 17:33:02 +00:00
2014-08-12 17:35:29 +00:00
}
2014-08-12 17:33:02 +00:00
y = y << shift
2014-08-12 17:35:29 +00:00
return y
2014-08-12 17:33:02 +00:00
}