File tree Expand file tree Collapse file tree 1 file changed +4
-6
lines changed Expand file tree Collapse file tree 1 file changed +4
-6
lines changed Original file line number Diff line number Diff line change @@ -20,24 +20,22 @@ public func gcd<T: BinaryInteger>(_ a: T, _ b: T) -> T {
20
20
var x = a. magnitude
21
21
var y = b. magnitude
22
22
23
- if x == 0 { return T ( y) }
24
23
if y == 0 { return T ( x) }
25
24
26
25
let xtz = x. trailingZeroBitCount
27
26
let ytz = y. trailingZeroBitCount
28
27
29
- x >>= xtz
30
28
y >>= ytz
31
29
32
30
// The binary GCD algorithm
33
31
//
34
- // At the top of the loop both x and y are odd. Each pass removes at least
35
- // one low-order bit from the larger of the two, so the number of iterations
36
- // is bounded by the sum of the bit-widths of the inputs.
32
+ // After the right-shift in the loop, both x and y are odd. Each pass removes
33
+ // at least one low-order bit from the larger of the two, so the number of
34
+ // iterations is bounded by the sum of the bit-widths of the inputs.
37
35
while x != 0 {
36
+ x >>= x. trailingZeroBitCount
38
37
if x < y { swap ( & x, & y) }
39
38
x -= y
40
- x >>= x. trailingZeroBitCount
41
39
}
42
40
43
41
return T ( y << min ( xtz, ytz) )
You can’t perform that action at this time.
0 commit comments