mirror of
https://github.com/TheAlgorithms/Ruby
synced 2024-12-26 21:58:56 +01:00
extended_euclidean_algorithm.rb
This commit is contained in:
parent
ca83061afe
commit
a3e9ee2ece
1 changed files with 31 additions and 0 deletions
31
discrete_mathematics/exteded_euclidean_algorithm.rb
Normal file
31
discrete_mathematics/exteded_euclidean_algorithm.rb
Normal file
|
@ -0,0 +1,31 @@
|
||||||
|
# https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
|
||||||
|
|
||||||
|
def extended_euclidean_gcd(a, b)
|
||||||
|
|
||||||
|
x0, x1 = a, b
|
||||||
|
s, t = 1, 0
|
||||||
|
until x1.zero?
|
||||||
|
q, x2 = x0.divmod(x1)
|
||||||
|
x0, x1 = x1, x2
|
||||||
|
s, t = t, s - q * t
|
||||||
|
end
|
||||||
|
gcd = x0
|
||||||
|
return gcd
|
||||||
|
end
|
||||||
|
|
||||||
|
puts "GCD(3, 5) = " + extended_euclidean_gcd(3, 5).to_s
|
||||||
|
# GCD(3, 6) = 3
|
||||||
|
puts "GCD(3, 6) = " + extended_euclidean_gcd(3, 6).to_s
|
||||||
|
# GCD(3, 6) = 3
|
||||||
|
puts "GCD(6, 3) = " + extended_euclidean_gcd(6, 3).to_s
|
||||||
|
# GCD(6, 3) = 3
|
||||||
|
|
||||||
|
=begin
|
||||||
|
|
||||||
|
Dynamic driver code:
|
||||||
|
|
||||||
|
a = gets.to_i
|
||||||
|
b = gets.to_i
|
||||||
|
puts "GCD (#{a}, #{b} ) = #{extended_euclidean_gcd(a, b)}"
|
||||||
|
|
||||||
|
=end
|
Loading…
Reference in a new issue