diff --git a/contents/euclidean_algorithm/code/ruby/euclidean.rb b/contents/euclidean_algorithm/code/ruby/euclidean.rb new file mode 100644 index 000000000..b8667ad71 --- /dev/null +++ b/contents/euclidean_algorithm/code/ruby/euclidean.rb @@ -0,0 +1,25 @@ +def gcd_mod(a, b) + a = a.abs + b = b.abs + a, b = b, a%b until b.zero? + a +end + +def gcd_minus(a, b) + a = a.abs + b = b.abs + until a == b + if a > b + a -= b + else + b -= a + end + end + a +end + +p gcd_mod(12 * 6, 12 * 4) #=> 12 +p gcd_mod(9 * 667, 9 * 104) #=> 9 + +p gcd_minus(12 * 6, 12 * 4) #=> 12 +p gcd_minus(9 * 667, 9 * 104) #=> 9 diff --git a/contents/euclidean_algorithm/euclidean_algorithm.md b/contents/euclidean_algorithm/euclidean_algorithm.md index 289bfcb51..d105645ba 100644 --- a/contents/euclidean_algorithm/euclidean_algorithm.md +++ b/contents/euclidean_algorithm/euclidean_algorithm.md @@ -45,6 +45,8 @@ The algorithm is a simple way to find the *greatest common divisor* (GCD) of two [import:3-8, lang="scala"](code/scala/euclidean.scala) {% sample lang="racket" %} [import:3-14, lang="lisp"](code/racket/euclidean_algorithm.rkt) +{% sample lang="ruby" %} +[import:8-19, lang="ruby"](code/ruby/euclidean.rb) {% sample lang="st" %} [import:1-13, lang="smalltalk"](code/smalltalk/euclid.st) {% endmethod %} @@ -98,6 +100,8 @@ Modern implementations, though, often use the modulus operator (%) like so [import:10-14, lang="scala"](code/scala/euclidean.scala) {% sample lang="racket" %} [import:16-24, lang="lisp"](code/racket/euclidean_algorithm.rkt) +{% sample lang="ruby" %} +[import:1-6, lang="ruby"](code/ruby/euclidean.rb) {% sample lang="st" %} [import:15-25, lang="smalltalk"](code/smalltalk/euclid.st) {% endmethod %} @@ -156,6 +160,8 @@ The Euclidean Algorithm is truly fundamental to many other algorithms throughout [import, lang="scala"](code/scala/euclidean.scala) {% sample lang="racket" %} [import, lang="lisp"](code/racket/euclidean_algorithm.rkt) +{% sample lang="ruby" %} +[import, lang="ruby"](code/ruby/euclidean.rb) {% sample lang="st" %} [import, lang="smalltalk"](code/smalltalk/euclid.st) {% endmethod %}