mirror of
https://github.com/apple/swift-numerics
synced 2026-11-30 05:28:47 +00:00
Simplified gcd implementation
This commit is contained in:
1 parent
83c378f2f4
commit
67af2fe0d9
1 file changed
+4
-6
@@ -20,24 +20,22 @@ public func gcd<T: BinaryInteger>(_ a: T, _ b: T) -> T {
|
||||
var x = a.magnitude
|
||||
var y = b.magnitude
|
||||
|
||||
if x == 0 { return T(y) }
|
||||
if y == 0 { return T(x) }
|
||||
|
||||
let xtz = x.trailingZeroBitCount
|
||||
let ytz = y.trailingZeroBitCount
|
||||
|
||||
x >>= xtz
|
||||
y >>= ytz
|
||||
|
||||
// The binary GCD algorithm
|
||||
//
|
||||
// At the top of the loop both x and y are odd. Each pass removes at least
|
||||
// one low-order bit from the larger of the two, so the number of iterations
|
||||
// is bounded by the sum of the bit-widths of the inputs.
|
||||
// After the right-shift in the loop, both x and y are odd. Each pass removes
|
||||
// at least one low-order bit from the larger of the two, so the number of
|
||||
// iterations is bounded by the sum of the bit-widths of the inputs.
|
||||
while x != 0 {
|
||||
x >>= x.trailingZeroBitCount
|
||||
if x < y { swap(&x, &y) }
|
||||
x -= y
|
||||
x >>= x.trailingZeroBitCount
|
||||
}
|
||||
|
||||
return T(y << min(xtz, ytz))
|
||||
|
||||
Reference in new issue
Block a user