File tree Expand file tree Collapse file tree 1 file changed +6
-2
lines changed Expand file tree Collapse file tree 1 file changed +6
-2
lines changed Original file line number Diff line number Diff line change @@ -27,6 +27,7 @@ public func gcd<T: BinaryInteger>(_ a: T, _ b: T) -> T {
27
27
var x = a. magnitude
28
28
var y = b. magnitude
29
29
30
+ if x == 0 { return T ( y) }
30
31
if y == 0 { return T ( x) }
31
32
32
33
let xtz = x. trailingZeroBitCount
@@ -39,11 +40,14 @@ public func gcd<T: BinaryInteger>(_ a: T, _ b: T) -> T {
39
40
// After the right-shift in the loop, both x and y are odd. Each pass removes
40
41
// at least one low-order bit from the larger of the two, so the number of
41
42
// iterations is bounded by the sum of the bit-widths of the inputs.
42
- while x != 0 {
43
+ //
44
+ // A tighter bound is the maximum bit-width of the inputs, which is achieved
45
+ // by odd numbers that sum to a power of 2, though the proof is more involved.
46
+ repeat {
43
47
x >>= x. trailingZeroBitCount
44
48
if x < y { swap ( & x, & y) }
45
49
x -= y
46
- }
50
+ } while x != 0
47
51
48
52
return T ( y << min ( xtz, ytz) )
49
53
}
You can’t perform that action at this time.
0 commit comments