Last active
January 29, 2022 14:16
-
-
Save gpfeiffer/4013925 to your computer and use it in GitHub Desktop.
Extended Euclidean 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
############################################################################# | |
## | |
## extended_gcd.rb | |
## | |
## given non-negative integers a > b, compute | |
## coefficients s, t such that gcd(a, b) == s*a + t*b | |
## | |
def extended_gcd(a, b) | |
# trivial case first: gcd(a, 0) == 1*a + 0*0 | |
return 1, 0 if b == 0 | |
# recurse: a = q*b + r | |
q, r = a.divmod b | |
s, t = extended_gcd(b, r) | |
# compute and return coefficients: | |
# gcd(a, b) == gcd(b, r) == s*b + t*r == s*b + t*(a - q*b) | |
return t, s - q * t | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment