Created
March 17, 2018 05:00
-
-
Save jzakiya/be6dc0c3efab90e71761860d280512ef to your computer and use it in GitHub Desktop.
Iterative Stein's (binary) GCD (greatest common divisor) algorithm in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def gcd(a, b) | |
| return b if a.zero? | |
| return a if b.zero? | |
| k = 0 | |
| while (a | b).even? | |
| a >>= 1; b >>= 1; k += 1 | |
| end | |
| a >>= 1 while a.even? | |
| until b.zero? | |
| b >>= 1 while b.even? | |
| a, b = b, a if a > b | |
| b -= a | |
| end | |
| a << k | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment