Made gcd a free function

This commit is contained in:
NevinBR authored and GitHub committed 2021-08-30 17:28:44 -04:00
1 parent 4fbcb11f03
commit b8f452189b
1 file changed
+30 -33
+30 -33
View File
@@ -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<T: BinaryInteger>(_ 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))
}