Skip to content

Commit 93eed1c

Browse files
c252berquist
authored andcommitted
euclid algorithm in scheme (#582)
1 parent 2f0b7af commit 93eed1c

File tree

3 files changed

+25
-0
lines changed

3 files changed

+25
-0
lines changed

book.json

+4
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,10 @@
188188
{
189189
"lang": "piet",
190190
"name": "Piet"
191+
},
192+
{
193+
"lang": "ss",
194+
"name": "Scheme"
191195
}
192196
]
193197
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
(define (euclid-sub a b)
2+
(cond
3+
[(or (negative? a)(negative? b))(euclid-sub (abs a)(abs b))]
4+
[(eq? a b) a]
5+
[(> a b)(euclid-sub(- a b) b)]
6+
[else
7+
(euclid-sub a (- b a))]))
8+
9+
(define (euclid-mod a b)
10+
(if (zero? b)
11+
a
12+
(euclid-mod b (modulo a b))))
13+
14+
(display (euclid-mod (* 64 67) (* 64 81))) (newline)
15+
(display (euclid-sub (* 64 12) (* 64 27))) (newline)

contents/euclidean_algorithm/euclidean_algorithm.md

+6
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,8 @@ The algorithm is a simple way to find the *greatest common divisor* (GCD) of two
6565
[import:24-38, lang="bash"](code/bash/euclid.bash)
6666
{% sample lang="piet" %}
6767
> ![](code/piet/subtract/euclidian_algorithm_subtract_large.png) ![](code/piet/subtract/euclidian_algorithm_subtract.png)
68+
{% sample lang="ss" %}
69+
[import:1-7, lang="scheme"](code/scheme/euclidalg.ss)
6870
{% endmethod %}
6971

7072
Here, we simply line the two numbers up every step and subtract the lower value from the higher one every timestep. Once the two values are equal, we call that value the greatest common divisor. A graph of `a` and `b` as they change every step would look something like this:
@@ -136,6 +138,8 @@ Modern implementations, though, often use the modulus operator (%) like so
136138
[import:10-22, lang="bash"](code/bash/euclid.bash)
137139
{% sample lang="piet" %}
138140
> ![](code/piet/mod/euclidian_algorithm_mod_large.png) ![](code/piet/mod/euclidian_algorithm_mod.png)
141+
{% sample lang="ss" %}
142+
[import:9-12, lang="scheme"](code/scheme/euclidalg.ss)
139143
{% endmethod %}
140144

141145
Here, we set `b` to be the remainder of `a%b` and `a` to be whatever `b` was last timestep. Because of how the modulus operator works, this will provide the same information as the subtraction-based implementation, but when we show `a` and `b` as they change with time, we can see that it might take many fewer steps:
@@ -232,6 +236,8 @@ A text version of the program is provided for both versions.
232236
> ![](code/piet/mod/euclidian_algorithm_mod_large.png) ![](code/piet/mod/euclidian_algorithm_mod.png)
233237
234238
[import:126-146](code/piet/euclidian_algorithm.piet)
239+
{% sample lang="ss" %}
240+
[import:, lang="scheme"](code/scheme/euclidalg.ss)
235241
{% endmethod %}
236242

237243
<script>

0 commit comments

Comments
 (0)