Skip to content

Commit 67af2fe

Browse files
authored
Simplified gcd implementation
1 parent 83c378f commit 67af2fe

File tree

1 file changed

+4
-6
lines changed

1 file changed

+4
-6
lines changed

Sources/IntegerUtilities/GCD.swift

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,24 +20,22 @@ public func gcd<T: BinaryInteger>(_ a: T, _ b: T) -> T {
2020
var x = a.magnitude
2121
var y = b.magnitude
2222

23-
if x == 0 { return T(y) }
2423
if y == 0 { return T(x) }
2524

2625
let xtz = x.trailingZeroBitCount
2726
let ytz = y.trailingZeroBitCount
2827

29-
x >>= xtz
3028
y >>= ytz
3129

3230
// The binary GCD algorithm
3331
//
34-
// At the top of the loop both x and y are odd. Each pass removes at least
35-
// one low-order bit from the larger of the two, so the number of iterations
36-
// is bounded by the sum of the bit-widths of the inputs.
32+
// After the right-shift in the loop, both x and y are odd. Each pass removes
33+
// at least one low-order bit from the larger of the two, so the number of
34+
// iterations is bounded by the sum of the bit-widths of the inputs.
3735
while x != 0 {
36+
x >>= x.trailingZeroBitCount
3837
if x < y { swap(&x, &y) }
3938
x -= y
40-
x >>= x.trailingZeroBitCount
4139
}
4240

4341
return T(y << min(xtz, ytz))

0 commit comments

Comments
 (0)