Created
December 21, 2015 21:13
-
-
Save ripesunflower/e2c16aa08362d740b2c1 to your computer and use it in GitHub Desktop.
Binary euclidean recursive algorithm for gcd
This file contains 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 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