Skip to content

Instantly share code, notes, and snippets.

@jzakiya
Created March 17, 2018 05:00
Show Gist options
  • Save jzakiya/be6dc0c3efab90e71761860d280512ef to your computer and use it in GitHub Desktop.
Save jzakiya/be6dc0c3efab90e71761860d280512ef to your computer and use it in GitHub Desktop.
Iterative Stein's (binary) GCD (greatest common divisor) algorithm in Ruby
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