Skip to content

Commit be60d04

Browse files
author
someody42
committed
An implementation of Euclidean Algorithm in D
1 parent c53c762 commit be60d04

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import std.stdio;
2+
import std.math;
3+
4+
// Euclidean algorithm using modulus
5+
int euclid_mod(int a, int b) {
6+
int tmp;
7+
a = abs(a);
8+
b = abs(b);
9+
10+
while (b != 0) {
11+
tmp = a % b;
12+
a = b;
13+
b = tmp;
14+
}
15+
16+
return a;
17+
}
18+
19+
// Euclidean algorithm with subtraction
20+
int euclid_sub(int a, int b) {
21+
a = abs(a);
22+
b = abs(b);
23+
24+
while (a != b) {
25+
if (a > b) {
26+
a -= b;
27+
} else {
28+
b -= a;
29+
}
30+
}
31+
32+
return a;
33+
}
34+
35+
void main()
36+
{
37+
auto check1 = euclid_mod(64 * 67, 64 * 81);
38+
auto check2 = euclid_sub(128 * 12, 128 * 77);
39+
40+
writeln(check1,'\n',check2);
41+
}

contents/euclidean_algorithm/euclidean_algorithm.md

+6
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,8 @@ The algorithm is a simple way to find the *greatest common divisor* (GCD) of two
6565
[import:25-40, lang="LOLCODE"](code/lolcode/euclid.lol)
6666
{% sample lang="bash" %}
6767
[import:24-38, lang="bash"](code/bash/euclid.bash)
68+
{% sample lang="d" %}
69+
[import:19-33, lang="d"](code/d/euclidean_algorithm.d)
6870
{% sample lang="piet" %}
6971
> ![](code/piet/subtract/euclidian_algorithm_subtract_large.png) ![](code/piet/subtract/euclidian_algorithm_subtract.png)
7072
{% sample lang="ss" %}
@@ -140,6 +142,8 @@ Modern implementations, though, often use the modulus operator (%) like so
140142
[import:9-23, lang="LOLCODE"](code/lolcode/euclid.lol)
141143
{% sample lang="bash" %}
142144
[import:10-22, lang="bash"](code/bash/euclid.bash)
145+
{% sample lang="d" %}
146+
[import:4-17, lang="d"](code/d/euclidean_algorithm.d)
143147
{% sample lang="piet" %}
144148
> ![](code/piet/mod/euclidian_algorithm_mod_large.png) ![](code/piet/mod/euclidian_algorithm_mod.png)
145149
{% sample lang="ss" %}
@@ -229,6 +233,8 @@ and modulo method:
229233
[import, lang="LOLCODE"](code/lolcode/euclid.lol)
230234
{% sample lang="bash" %}
231235
[import, lang="bash"](code/bash/euclid.bash)
236+
{% sample lang="d" %}
237+
[import, lang="d"](code/d/euclidean_algorithm.d)
232238
{% sample lang="piet" %}
233239
A text version of the program is provided for both versions.
234240
#### Subtraction

0 commit comments

Comments
 (0)