diff --git a/contents/euclidean_algorithm/code/d/euclidean_algorithm.d b/contents/euclidean_algorithm/code/d/euclidean_algorithm.d new file mode 100644 index 000000000..042a9bae1 --- /dev/null +++ b/contents/euclidean_algorithm/code/d/euclidean_algorithm.d @@ -0,0 +1,42 @@ +import std.stdio; +import std.math; + +// Euclidean algorithm using modulus +int euclid_mod(int a, int b) { + int tmp; + a = abs(a); + b = abs(b); + + while (b != 0) { + tmp = a % b; + a = b; + b = tmp; + } + + return a; +} + +// Euclidean algorithm with subtraction +int euclid_sub(int a, int b) { + a = abs(a); + b = abs(b); + + while (a != b) { + if (a > b) { + a -= b; + } else { + b -= a; + } + } + + return a; +} + +void main() +{ + auto check1 = euclid_mod(64 * 67, 64 * 81); + auto check2 = euclid_sub(128 * 12, 128 * 77); + + writeln("Modulus-based euclidean algorithm result: ", check1); + writeln("Subtraction-based euclidean algorithm result: ", check2); +} diff --git a/contents/euclidean_algorithm/euclidean_algorithm.md b/contents/euclidean_algorithm/euclidean_algorithm.md index 967e4b5f9..4ff49152f 100644 --- a/contents/euclidean_algorithm/euclidean_algorithm.md +++ b/contents/euclidean_algorithm/euclidean_algorithm.md @@ -65,6 +65,8 @@ The algorithm is a simple way to find the *greatest common divisor* (GCD) of two [import:25-40, lang="LOLCODE"](code/lolcode/euclid.lol) {% sample lang="bash" %} [import:24-38, lang="bash"](code/bash/euclid.bash) +{% sample lang="d" %} +[import:19-33, lang="d"](code/d/euclidean_algorithm.d) {% sample lang="piet" %} > ![](code/piet/subtract/euclidian_algorithm_subtract_large.png) ![](code/piet/subtract/euclidian_algorithm_subtract.png) {% sample lang="ss" %} @@ -140,6 +142,8 @@ Modern implementations, though, often use the modulus operator (%) like so [import:9-23, lang="LOLCODE"](code/lolcode/euclid.lol) {% sample lang="bash" %} [import:10-22, lang="bash"](code/bash/euclid.bash) +{% sample lang="d" %} +[import:4-17, lang="d"](code/d/euclidean_algorithm.d) {% sample lang="piet" %} > ![](code/piet/mod/euclidian_algorithm_mod_large.png) ![](code/piet/mod/euclidian_algorithm_mod.png) {% sample lang="ss" %} @@ -229,6 +233,8 @@ and modulo method: [import, lang="LOLCODE"](code/lolcode/euclid.lol) {% sample lang="bash" %} [import, lang="bash"](code/bash/euclid.bash) +{% sample lang="d" %} +[import, lang="d"](code/d/euclidean_algorithm.d) {% sample lang="piet" %} A text version of the program is provided for both versions. #### Subtraction