Created
March 17, 2018 12:59
-
-
Save jzakiya/b096b92c181ed343dab8c130c88f1d39 to your computer and use it in GitHub Desktop.
Iterative Stein's (binary) GCD (greatest common divisor) algorithm in Nim
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
proc gcd(a, b: int): int = | |
var (a, b) = (a, b) | |
if a == 0: return b | |
if b == 0: return a | |
var k = 0 | |
while ((a or b) and 1) == 0: | |
a = a shr 1 | |
b = b shr 1 | |
k += 1 | |
while (a and 1) == 0: a = a shr 1 | |
while b != 0: | |
while (b and 1) == 0: b = b shr 1 | |
if a > b: swap a,b | |
b -= a | |
result = a shl k |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment