diff --git a/book.json b/book.json index ceb0d60b0..87f2728a1 100644 --- a/book.json +++ b/book.json @@ -116,6 +116,10 @@ { "lang": "ti83b", "name": "TI-83 Basic" + }, + { + "lang": "lua", + "name": "Lua" } ] } diff --git a/contents/euclidean_algorithm/code/lua/euclidean.lua b/contents/euclidean_algorithm/code/lua/euclidean.lua new file mode 100644 index 000000000..45ef1fd18 --- /dev/null +++ b/contents/euclidean_algorithm/code/lua/euclidean.lua @@ -0,0 +1,32 @@ +function euclidSub (a, b) + local a = math.abs(a) + local b = math.abs(b) + + while a ~= b do + if a > b then + a = a-b + else + b = b-a + end + end + + return a +end + +function euclidMod (a, b) + local a = math.abs(a) + local b = math.abs(b) + + while b ~= 0 do + a, b = b, a%b + end + + return a +end + +function main () + print(euclidSub(128 * 12, 128 * 77)) + print(euclidMod(64 * 67, 64 * 81)) +end + +main() diff --git a/contents/euclidean_algorithm/euclidean_algorithm.md b/contents/euclidean_algorithm/euclidean_algorithm.md index 707a04236..5529493d9 100644 --- a/contents/euclidean_algorithm/euclidean_algorithm.md +++ b/contents/euclidean_algorithm/euclidean_algorithm.md @@ -31,6 +31,8 @@ The algorithm is a simple way to find the *greatest common divisor* (GCD) of two [import:1-15, lang="swift"](code/swift/euclidean_algorithm.swift) {% sample lang="matlab" %} [import:3-17, lang="matlab"](code/matlab/euclidean.m) +{% sample lang="lua" %} +[import:1-14, lang="lua"](code/lua/euclidean.lua) {% 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: @@ -68,6 +70,8 @@ Modern implementations, though, often use the modulus operator (%) like so [import:17-29, lang="swift"](code/swift/euclidean_algorithm.swift) {% sample lang="matlab" %} [import:19-31, lang="matlab"](code/matlab/euclidean.m) +{% sample lang="lua" %} +[import:16-25, lang="lua"](code/lua/euclidean.lua) {% 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: @@ -110,6 +114,8 @@ Program.cs [import, lang="swift"](code/swift/euclidean_algorithm.swift) {% sample lang="matlab" %} [import, lang="matlab"](code/matlab/euclidean.m) +{% sample lang="lua" %} +[import, lang="lua"](code/lua/euclidean.lua) {% endmethod %}