Skip to content

Commit 759c563

Browse files
Wesley-Arringtonjiegillet
authored andcommitted
Adding Euclidean Algorithm in Lua (#293)
* Adding Euclidean Algorithm in Lua
1 parent 820d0d9 commit 759c563

File tree

3 files changed

+42
-0
lines changed

3 files changed

+42
-0
lines changed

book.json

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,10 @@
112112
{
113113
"lang": "ti83b",
114114
"name": "TI-83 Basic"
115+
},
116+
{
117+
"lang": "lua",
118+
"name": "Lua"
115119
}
116120
]
117121
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
function euclidSub (a, b)
2+
local a = math.abs(a)
3+
local b = math.abs(b)
4+
5+
while a ~= b do
6+
if a > b then
7+
a = a-b
8+
else
9+
b = b-a
10+
end
11+
end
12+
13+
return a
14+
end
15+
16+
function euclidMod (a, b)
17+
local a = math.abs(a)
18+
local b = math.abs(b)
19+
20+
while b ~= 0 do
21+
a, b = b, a%b
22+
end
23+
24+
return a
25+
end
26+
27+
function main ()
28+
print(euclidSub(128 * 12, 128 * 77))
29+
print(euclidMod(64 * 67, 64 * 81))
30+
end
31+
32+
main()

contents/euclidean_algorithm/euclidean_algorithm.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@ The algorithm is a simple way to find the *greatest common divisor* (GCD) of two
3131
[import:1-14, lang="swift"](code/swift/euclidean_algorithm.swift)
3232
{% sample lang="matlab" %}
3333
[import:3-17, lang="matlab"](code/matlab/euclidean.m)
34+
{% sample lang="lua" %}
35+
[import:1-14, lang="lua"](code/lua/euclidean.lua)
3436
{% endmethod %}
3537

3638
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
6870
[import:16-27, lang="swift"](code/swift/euclidean_algorithm.swift)
6971
{% sample lang="matlab" %}
7072
[import:19-31, lang="matlab"](code/matlab/euclidean.m)
73+
{% sample lang="lua" %}
74+
[import:16-25, lang="lua"](code/lua/euclidean.lua)
7175
{% endmethod %}
7276

7377
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
110114
[import, lang="swift"](code/swift/euclidean_algorithm.swift)
111115
{% sample lang="matlab" %}
112116
[import, lang="matlab"](code/matlab/euclidean.m)
117+
{% sample lang="lua" %}
118+
[import, lang="lua"](code/lua/euclidean.lua)
113119
{% endmethod %}
114120

115121

0 commit comments

Comments
 (0)