mirror of
https://github.com/apple/swift-numerics
synced 2026-11-26 04:57:53 +00:00
Made gcd a free function
This commit is contained in:
1 parent
4fbcb11f03
commit
b8f452189b
1 file changed
+30
-33
@@ -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))
|
||||
}
|
||||
Reference in new issue
Block a user