diff --git a/book.json b/book.json index 01d7d0acf..1b62ffae8 100644 --- a/book.json +++ b/book.json @@ -163,6 +163,10 @@ { "lang": "lolcode", "name": "LOLCODE" + }, + { + "lang": "sh", + "name": "Bash" } ] } diff --git a/contents/euclidean_algorithm/code/bash/euclid.bash b/contents/euclidean_algorithm/code/bash/euclid.bash new file mode 100755 index 000000000..bef4b5da0 --- /dev/null +++ b/contents/euclidean_algorithm/code/bash/euclid.bash @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +abs() { + local ret=$1 + if (( ret < 0 )); then + ((ret *= -1)) + fi + printf "%s" "$ret" +} + +euclid_mod() { + local a + local b + a=$(abs "$1") + b=$(abs "$2") + + while (( b != 0 )); do + ((tmp = b)) + ((b = a % b)) + ((a = tmp)) + done + printf "%s" "$a" +} + +euclid_sub() { + local a + local b + a=$(abs "$1") + b=$(abs "$2") + + while (( a != b )); do + if (( a > b )); then + ((a -= b)) + else + ((b -= a)) + fi + done + printf "%s" "$a" +} + +result=$(euclid_mod $((64 * 67)) $((64 * 81))) +echo "$result" +result=$(euclid_sub $((128 * 12)) $((128 * 77))) +echo "$result" diff --git a/contents/euclidean_algorithm/euclidean_algorithm.md b/contents/euclidean_algorithm/euclidean_algorithm.md index a85027d1a..68a34ab04 100644 --- a/contents/euclidean_algorithm/euclidean_algorithm.md +++ b/contents/euclidean_algorithm/euclidean_algorithm.md @@ -59,6 +59,8 @@ The algorithm is a simple way to find the *greatest common divisor* (GCD) of two [import:2-17, lang:"emojicode"](code/emojicode/euclidean_algorithm.emojic) {% sample lang="lolcode" %} [import:25-40, lang="LOLCODE"](code/lolcode/euclid.lol) +{% sample lang="bash" %} +[import:24-38, lang="bash"](code/bash/euclid.bash) {% endmethod %} 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: @@ -124,6 +126,8 @@ Modern implementations, though, often use the modulus operator (%) like so [import:19-31, lang:"emojicode"](code/emojicode/euclidean_algorithm.emojic) {% sample lang="lolcode" %} [import:9-23, lang="LOLCODE"](code/lolcode/euclid.lol) +{% sample lang="bash" %} +[import:10-22, lang="bash"](code/bash/euclid.bash) {% endmethod %} 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: @@ -197,8 +201,11 @@ and modulo method: [import, lang:"emojicode"](code/emojicode/euclidean_algorithm.emojic) {% sample lang="lolcode" %} [import, lang="LOLCODE"](code/lolcode/euclid.lol) +{% sample lang="bash" %} +[import, lang="bash"](code/bash/euclid.bash) {% endmethod %} +