Skip to content

Instantly share code, notes, and snippets.

@gpfeiffer
Last active January 29, 2022 14:16
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save gpfeiffer/4013925 to your computer and use it in GitHub Desktop.
Save gpfeiffer/4013925 to your computer and use it in GitHub Desktop.
Extended Euclidean Algorithm in Ruby
#############################################################################
##
## 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