Skip to content

Instantly share code, notes, and snippets.

@lauslim12
Last active October 10, 2018 05:23
Show Gist options
  • Save lauslim12/8d8790b7572e0443cfc4c14e49579a47 to your computer and use it in GitHub Desktop.
Save lauslim12/8d8790b7572e0443cfc4c14e49579a47 to your computer and use it in GitHub Desktop.
Finding the greatest common divisor + Bézout's identity. I use Ruby's built in function.
def gcd(a, b)
return a if b == 0
return b if a == 0
a.gcd(b)
end
def bezout(a, b)
return 1, 0 if b == 0
q, r = a.divmod b
s, t = bezout(b, r)
return t, s - q * t
end
puts "Input two numbers to find the Greatest Common Divisor."
puts "Bonus: Bézout's identity is provided."
z = 0
while z == 0
i = gets.to_i
j = gets.to_i
puts gcd(i, j)
puts bezout(i, j)
puts "Calculate again? 1/2"
z = gets.to_i
if z == 1 then
z = 0
elsif z == 2 then
z = z+1
else
puts "Undefined."
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment