Commit Graph
7 Commits
Author SHA1 Message Date
NevinBR 7f2d022d3d GCD bug fix
The standard-library documentation for `trailingZeroBitCount` states:

> If the value is zero, then `trailingZeroBitCount` is equal to `bitWidth`.

Thus, if `T` is not a fixed-width integer type, and `x == 0`, and `y` has more trailing zeros than the representation of `x`, then the gcd calculation will be incorrect.

In particular, the left-shift by `min(xtz, ytz) == xtz` will not “undo” the earlier right-shift by `ytz`,  so the final result will be incorrectly right-shifted by `ytz - xtz`.

To fix this I have added an early exit when `x == 0`. I am not sure if this is the optimal solution, and I’m open to alternatives.

***

This change ensures that `x != 0` at the top of the loop, so I have also converted it from a `while` to a `repeat-while` loop, in order to eliminate a redundant extra comparison on the first iteration.

I don’t know if this actually affects performance, and I’m happy to change it back if that’s preferred.
2022-02-22 11:46:06 -05:00
NevinBR 85264c808c Reworded doc comment for gcd 2021-09-09 23:05:45 -04:00
NevinBR 8552becf91 Documented overflow behavior of gcd 2021-08-31 11:19:22 -04:00
NevinBR 67af2fe0d9 Simplified gcd implementation 2021-08-30 17:32:03 -04:00
NevinBR b8f452189b Made gcd a free function 2021-08-30 17:28:44 -04:00
NevinBR 4fbcb11f03 Improved GCD documentation 2021-08-26 19:49:13 -04:00
NevinBR 909a77c3d9 Create GCD.swift
Binary GCD algorithm
2021-08-26 14:51:05 -04:00