diff --git a/contents/euclidean_algorithm/code/julia/euclidean.jl b/contents/euclidean_algorithm/code/julia/euclidean.jl new file mode 100644 index 000000000..744ae2187 --- /dev/null +++ b/contents/euclidean_algorithm/code/julia/euclidean.jl @@ -0,0 +1,36 @@ +function euclid_mod(a::Int64, b::Int64) + a = abs(a) + b = abs(b) + + while(b != 0) + b,a = a%b,b + end + + return a +end + +function euclid_sub(a::Int64, b::Int64) + a = abs(a) + b = abs(b) + + while (a != b) + if (a > b) + a -= b + else + b -= a + end + end + + return a +end + +function main() + check1 = euclid_mod(64 * 67, 64 * 81); + check2 = euclid_sub(128 * 12, 128 * 77); + + println("Modulus-based euclidean algorithm result: $(check1)") + println("subtraction-based euclidean algorithm result: $(check2)") + +end + +main() diff --git a/contents/euclidean_algorithm/euclidean_algorithm.md b/contents/euclidean_algorithm/euclidean_algorithm.md index 5167c29c3..7cfe043a5 100644 --- a/contents/euclidean_algorithm/euclidean_algorithm.md +++ b/contents/euclidean_algorithm/euclidean_algorithm.md @@ -33,6 +33,8 @@ The algorithm is a simple way to find the *greatest common divisor* (GCD) of two [import:3-17, lang="matlab"](code/matlab/euclidean.m) {% sample lang="lua" %} [import:1-14, lang="lua"](code/lua/euclidean.lua) +{% sample lang="jl" %} +[import:1-10, lang="julia"](code/julia/euclidean.jl) {% 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: @@ -72,6 +74,8 @@ Modern implementations, though, often use the modulus operator (%) like so [import:19-31, lang="matlab"](code/matlab/euclidean.m) {% sample lang="lua" %} [import:16-25, lang="lua"](code/lua/euclidean.lua) +{% sample lang="jl" %} +[import:12-25, lang="julia"](code/julia/euclidean.jl) {% 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: @@ -116,6 +120,8 @@ Program.cs [import, lang="matlab"](code/matlab/euclidean.m) {% sample lang="lua" %} [import, lang="lua"](code/lua/euclidean.lua) +{% sample lang="jl" %} +[import, lang="julia"](code/julia/euclidean.jl) {% endmethod %}