diff --git a/contents/euclidean_algorithm/code/crystal/euclidean.cr b/contents/euclidean_algorithm/code/crystal/euclidean.cr new file mode 100644 index 000000000..09a74429f --- /dev/null +++ b/contents/euclidean_algorithm/code/crystal/euclidean.cr @@ -0,0 +1,37 @@ +def euclid_mod(a : Int, b : Int) + a = a.abs + b = b.abs + + loop do + b, a = a % b, b + break if b == 0 + end + + return a +end + +def euclid_sub(a : Int, b : Int) + a = a.abs + b = b.abs + + loop do + if a > b + a -= b + else + b -= a + end + break if a == b + end + + return a +end + +def main + euc_mod = euclid_mod(64 * 67, 64 * 81) + euc_sub = euclid_sub(128 * 12, 128 * 77) + + puts "Modulus-based euclidean algorithm result: #{euc_mod}" + puts "Subtraction-based euclidean algorithm result: #{euc_sub}" +end + +main \ No newline at end of file diff --git a/contents/euclidean_algorithm/euclidean_algorithm.md b/contents/euclidean_algorithm/euclidean_algorithm.md index 82aa64a2a..02aaf2787 100644 --- a/contents/euclidean_algorithm/euclidean_algorithm.md +++ b/contents/euclidean_algorithm/euclidean_algorithm.md @@ -83,6 +83,8 @@ The algorithm is a simple way to find the *greatest common divisor* (GCD) of two [import:1-14, lang="powershell"](code/powershell/euclidean_algorithm.ps1) {% sample lang="coco" %} [import:1-9, lang="coconut"](code/coconut/euclidean.coco) +{% sample lang="crystal" %} +[import:13-27, lang="crystal"](code/crystal/euclidean.cr) {% endmethod %} @@ -173,6 +175,8 @@ Modern implementations, though, often use the modulus operator (%) like so [import:16-27, lang="powershell"](code/powershell/euclidean_algorithm.ps1) {% sample lang="coco" %} [import:12-15, lang="coconut"](code/coconut/euclidean.coco) +{% sample lang="crystal" %} +[import:1-11, lang="crystal"](code/crystal/euclidean.cr) {% endmethod %} @@ -290,6 +294,8 @@ The code snippets were taken from this [Scratch project](https://scratch.mit.edu [import, lang="powershell"](code/powershell/euclidean_algorithm.ps1) {% sample lang="coco" %} [import, lang="coconut"](code/coconut/euclidean.coco) +{% sample lang="crystal" %} +[import, lang="crystal"](code/crystal/euclidean.cr) {% endmethod %}