From 67af2fe0d9c360869a70bf9798cf3afa8163005e Mon Sep 17 00:00:00 2001 From: NevinBR Date: Mon, 30 Aug 2021 17:32:03 -0400 Subject: [PATCH] Simplified gcd implementation --- Sources/IntegerUtilities/GCD.swift | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/Sources/IntegerUtilities/GCD.swift b/Sources/IntegerUtilities/GCD.swift index f67014a..3e6afdf 100644 --- a/Sources/IntegerUtilities/GCD.swift +++ b/Sources/IntegerUtilities/GCD.swift @@ -20,24 +20,22 @@ public func gcd(_ 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))