Skip to content

Instantly share code, notes, and snippets.

@ripesunflower
Created December 21, 2015 21:13
Show Gist options
  • Save ripesunflower/e2c16aa08362d740b2c1 to your computer and use it in GitHub Desktop.
Save ripesunflower/e2c16aa08362d740b2c1 to your computer and use it in GitHub Desktop.
Binary euclidean recursive algorithm for gcd
def find_gcd(a, b)
if a == 0; b
elsif b == 0; a
elsif a == b; a
elsif a == 1 || b == 1; 1
elsif a.even? && b.even?; 2 * find_gcd(a / 2, b / 2)
elsif a.even? && b.odd?; find_gcd(a / 2, b)
elsif a.odd? && b.even?; find_gcd(a, b / 2)
elsif a.odd? && b.odd?; (b > a) ? find_gcd((b - a) / 2, a) : find_gcd((a - b) / 2, b)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment