From b8f452189bc15f8a21cef4471c828c136af6acdd Mon Sep 17 00:00:00 2001 From: NevinBR Date: Mon, 30 Aug 2021 17:28:44 -0400 Subject: [PATCH] Made gcd a free function --- Sources/IntegerUtilities/GCD.swift | 63 ++++++++++++++---------------- 1 file changed, 30 insertions(+), 33 deletions(-) diff --git a/Sources/IntegerUtilities/GCD.swift b/Sources/IntegerUtilities/GCD.swift index c8c2400..f67014a 100644 --- a/Sources/IntegerUtilities/GCD.swift +++ b/Sources/IntegerUtilities/GCD.swift @@ -9,39 +9,36 @@ // //===----------------------------------------------------------------------===// -extension BinaryInteger { +/// The greatest common divisor of `a` and `b`. +/// +/// If both inputs are zero, the result is zero. If one input is zero, the +/// result is the absolute value of the other input. +/// +/// [wiki]: https://en.wikipedia.org/wiki/Greatest_common_divisor +@inlinable +public func gcd(_ a: T, _ b: T) -> T { + var x = a.magnitude + var y = b.magnitude - /// The greatest common divisor of `a` and `b`. - /// - /// If both inputs are zero, the result is zero. If one input is zero, the - /// result is the absolute value of the other input. - /// - /// [wiki]: https://en.wikipedia.org/wiki/Greatest_common_divisor - @inlinable - public static func gcd(_ a: Self, _ b: Self) -> Self { - var x = a.magnitude - var y = b.magnitude - - if x == 0 { return Self(y) } - if y == 0 { return Self(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. - while x != 0 { - if x < y { swap(&x, &y) } - x -= y - x >>= x.trailingZeroBitCount - } - - return Self(y << min(xtz, ytz)) + 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. + while x != 0 { + if x < y { swap(&x, &y) } + x -= y + x >>= x.trailingZeroBitCount } + + return T(y << min(xtz, ytz)) }