Skip to content

Commit 8c5139c

Browse files
authored
Merge pull request #340 from leios/julia_euclid
adding julia version of euclidean algorithm
2 parents 7f9434a + 42fcfc1 commit 8c5139c

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
function euclid_mod(a::Int64, b::Int64)
2+
a = abs(a)
3+
b = abs(b)
4+
5+
while(b != 0)
6+
b,a = a%b,b
7+
end
8+
9+
return a
10+
end
11+
12+
function euclid_sub(a::Int64, b::Int64)
13+
a = abs(a)
14+
b = abs(b)
15+
16+
while (a != b)
17+
if (a > b)
18+
a -= b
19+
else
20+
b -= a
21+
end
22+
end
23+
24+
return a
25+
end
26+
27+
function main()
28+
check1 = euclid_mod(64 * 67, 64 * 81);
29+
check2 = euclid_sub(128 * 12, 128 * 77);
30+
31+
println("Modulus-based euclidean algorithm result: $(check1)")
32+
println("subtraction-based euclidean algorithm result: $(check2)")
33+
34+
end
35+
36+
main()

contents/euclidean_algorithm/euclidean_algorithm.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@ The algorithm is a simple way to find the *greatest common divisor* (GCD) of two
3333
[import:3-17, lang="matlab"](code/matlab/euclidean.m)
3434
{% sample lang="lua" %}
3535
[import:1-14, lang="lua"](code/lua/euclidean.lua)
36+
{% sample lang="jl" %}
37+
[import:1-10, lang="julia"](code/julia/euclidean.jl)
3638
{% endmethod %}
3739

3840
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:
@@ -72,6 +74,8 @@ Modern implementations, though, often use the modulus operator (%) like so
7274
[import:19-31, lang="matlab"](code/matlab/euclidean.m)
7375
{% sample lang="lua" %}
7476
[import:16-25, lang="lua"](code/lua/euclidean.lua)
77+
{% sample lang="jl" %}
78+
[import:12-25, lang="julia"](code/julia/euclidean.jl)
7579
{% endmethod %}
7680

7781
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:
@@ -116,6 +120,8 @@ Program.cs
116120
[import, lang="matlab"](code/matlab/euclidean.m)
117121
{% sample lang="lua" %}
118122
[import, lang="lua"](code/lua/euclidean.lua)
123+
{% sample lang="jl" %}
124+
[import, lang="julia"](code/julia/euclidean.jl)
119125
{% endmethod %}
120126

121127

0 commit comments

Comments
 (0)