TheAlgorithms-Ruby/discrete_mathematics/exteded_euclidean_algorithm.rb

31 lines
575 B
Ruby
Raw Normal View History

2021-01-22 09:08:45 +01:00
# https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
def extended_euclidean_gcd(a, b)
2021-02-07 08:05:54 +01:00
x0 = a
x1 = b
s = 1
t = 0
2021-01-22 09:08:45 +01:00
until x1.zero?
q, x2 = x0.divmod(x1)
2021-02-07 08:05:54 +01:00
x0 = x1
x1 = x2
2021-01-22 09:08:45 +01:00
s, t = t, s - q * t
end
2021-02-07 08:05:54 +01:00
x0
2021-01-22 09:08:45 +01:00
end
2021-02-07 08:05:54 +01:00
puts 'GCD(3, 5) = ' + extended_euclidean_gcd(3, 5).to_s
2021-01-25 17:43:23 +01:00
# GCD(3, 5) = 1
2021-02-07 08:05:54 +01:00
puts 'GCD(3, 6) = ' + extended_euclidean_gcd(3, 6).to_s
2021-01-22 09:08:45 +01:00
# GCD(3, 6) = 3
2021-02-07 08:05:54 +01:00
puts 'GCD(6, 3) = ' + extended_euclidean_gcd(6, 3).to_s
2021-01-22 09:08:45 +01:00
# GCD(6, 3) = 3
2021-02-07 08:05:54 +01:00
#
# Dynamic driver code:
#
# a = gets.to_i
# b = gets.to_i
# puts "GCD (#{a}, #{b} ) = #{extended_euclidean_gcd(a, b)}"
#