Skip to content

Commit ef58ca9

Browse files
Nic Hartleyjiegillet
Nic Hartley
authored andcommitted
Add Euclidean algorithm in Ruby (#447)
* Add code * Add it to the page * Add absolute value, about to update .md file * Updated line numbers * Factorized arguments for clarity
1 parent 5547921 commit ef58ca9

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
def gcd_mod(a, b)
2+
a = a.abs
3+
b = b.abs
4+
a, b = b, a%b until b.zero?
5+
a
6+
end
7+
8+
def gcd_minus(a, b)
9+
a = a.abs
10+
b = b.abs
11+
until a == b
12+
if a > b
13+
a -= b
14+
else
15+
b -= a
16+
end
17+
end
18+
a
19+
end
20+
21+
p gcd_mod(12 * 6, 12 * 4) #=> 12
22+
p gcd_mod(9 * 667, 9 * 104) #=> 9
23+
24+
p gcd_minus(12 * 6, 12 * 4) #=> 12
25+
p gcd_minus(9 * 667, 9 * 104) #=> 9

contents/euclidean_algorithm/euclidean_algorithm.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,8 @@ The algorithm is a simple way to find the *greatest common divisor* (GCD) of two
4545
[import:3-8, lang="scala"](code/scala/euclidean.scala)
4646
{% sample lang="racket" %}
4747
[import:3-14, lang="lisp"](code/racket/euclidean_algorithm.rkt)
48+
{% sample lang="ruby" %}
49+
[import:8-19, lang="ruby"](code/ruby/euclidean.rb)
4850
{% sample lang="st" %}
4951
[import:1-13, lang="smalltalk"](code/smalltalk/euclid.st)
5052
{% endmethod %}
@@ -98,6 +100,8 @@ Modern implementations, though, often use the modulus operator (%) like so
98100
[import:10-14, lang="scala"](code/scala/euclidean.scala)
99101
{% sample lang="racket" %}
100102
[import:16-24, lang="lisp"](code/racket/euclidean_algorithm.rkt)
103+
{% sample lang="ruby" %}
104+
[import:1-6, lang="ruby"](code/ruby/euclidean.rb)
101105
{% sample lang="st" %}
102106
[import:15-25, lang="smalltalk"](code/smalltalk/euclid.st)
103107
{% endmethod %}
@@ -156,6 +160,8 @@ The Euclidean Algorithm is truly fundamental to many other algorithms throughout
156160
[import, lang="scala"](code/scala/euclidean.scala)
157161
{% sample lang="racket" %}
158162
[import, lang="lisp"](code/racket/euclidean_algorithm.rkt)
163+
{% sample lang="ruby" %}
164+
[import, lang="ruby"](code/ruby/euclidean.rb)
159165
{% sample lang="st" %}
160166
[import, lang="smalltalk"](code/smalltalk/euclid.st)
161167
{% endmethod %}

0 commit comments

Comments
 (0)