Skip to content

Commit 6d02f4e

Browse files
authored
Euclidean algorithm in coconut (#721)
1 parent 28896b9 commit 6d02f4e

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

book.json

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,10 @@
212212
{
213213
"lang": "vim",
214214
"name": "VimL"
215+
},
216+
{
217+
"lang": "coco",
218+
"name": "Coconut"
215219
}
216220
]
217221
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
def euclid_sub(a is int, 0) = a
2+
addpattern def euclid_sub(0, b is int) = b
3+
4+
addpattern def euclid_sub(a is int, b is int):
5+
if a < b:
6+
return euclid_sub(a, b - a)
7+
elif b < a:
8+
return euclid_sub(a - b, b)
9+
return a
10+
11+
12+
def euclid_mod(a is int, 0) = a
13+
addpattern def euclid_mod(0, b is int) = b
14+
15+
addpattern def euclid_mod(a is int, b is int) = euclid_mod(b, a % b)
16+
17+
if __name__ == '__main__':
18+
print('Euclidean mod:', euclid_mod(64 * 67, 64 * 81))
19+
print('Euclidean sub:', euclid_sub(128 * 12, 128 * 77))

contents/euclidean_algorithm/euclidean_algorithm.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,8 @@ The algorithm is a simple way to find the *greatest common divisor* (GCD) of two
8181

8282
{% sample lang="ps1" %}
8383
[import:1-14, lang="powershell"](code/powershell/euclidean_algorithm.ps1)
84+
{% sample lang="coco" %}
85+
[import:1-9, lang="coconut"](code/coconut/euclidean.coco)
8486

8587
{% endmethod %}
8688

@@ -169,6 +171,8 @@ Modern implementations, though, often use the modulus operator (%) like so
169171

170172
{% sample lang="ps1" %}
171173
[import:16-27, lang="powershell"](code/powershell/euclidean_algorithm.ps1)
174+
{% sample lang="coco" %}
175+
[import:12-15, lang="coconut"](code/coconut/euclidean.coco)
172176

173177
{% endmethod %}
174178

@@ -282,6 +286,8 @@ The code snippets were taken from this [Scratch project](https://scratch.mit.edu
282286

283287
{% sample lang="ps1" %}
284288
[import, lang="powershell"](code/powershell/euclidean_algorithm.ps1)
289+
{% sample lang="coco" %}
290+
[import, lang="coconut"](code/coconut/euclidean.coco)
285291

286292
{% endmethod %}
287293

0 commit comments

Comments
 (0)