Skip to content

Euclidean algorithm in coconut #721

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions book.json
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,10 @@
{
"lang": "vim",
"name": "VimL"
},
{
"lang": "coco",
"name": "Coconut"
}
]
}
Expand Down
19 changes: 19 additions & 0 deletions contents/euclidean_algorithm/code/coconut/euclidean.coco
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
def euclid_sub(a is int, 0) = a
addpattern def euclid_sub(0, b is int) = b

addpattern def euclid_sub(a is int, b is int):
if a < b:
return euclid_sub(a, b - a)
elif b < a:
return euclid_sub(a - b, b)
return a


def euclid_mod(a is int, 0) = a
addpattern def euclid_mod(0, b is int) = b

addpattern def euclid_mod(a is int, b is int) = euclid_mod(b, a % b)

if __name__ == '__main__':
print('Euclidean mod:', euclid_mod(64 * 67, 64 * 81))
print('Euclidean sub:', euclid_sub(128 * 12, 128 * 77))
6 changes: 6 additions & 0 deletions contents/euclidean_algorithm/euclidean_algorithm.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ The algorithm is a simple way to find the *greatest common divisor* (GCD) of two

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

{% endmethod %}

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

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

{% endmethod %}

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

{% sample lang="ps1" %}
[import, lang="powershell"](code/powershell/euclidean_algorithm.ps1)
{% sample lang="coco" %}
[import, lang="coconut"](code/coconut/euclidean.coco)

{% endmethod %}

Expand Down