Skip to content

Commit 39656d5

Browse files
Wesley-Arringtonjiegillet
authored andcommitted
Adding Euclidean Algorithm in Swift (#231)
- Adding Euclidean Algorithm in Swift
1 parent b4429b9 commit 39656d5

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
func euclidSub(a: Int, b: Int) -> Int {
2+
var A = abs(a)
3+
var B = abs(b)
4+
5+
while (A != B) {
6+
if (A > B) {
7+
A -= B
8+
} else {
9+
B -= A
10+
}
11+
}
12+
13+
return A
14+
}
15+
16+
17+
func euclidMod(a: Int, b: Int) -> Int {
18+
var A = abs(a);
19+
var B = abs(b);
20+
21+
while (B != 0) {
22+
let temp = B
23+
B = A % B
24+
A = temp
25+
}
26+
27+
return A
28+
}
29+
30+
31+
32+
33+
func main() {
34+
print(euclidMod(a: 64 * 67, b: 64 * 81))
35+
print(euclidSub(a: 128 * 12, b: 128 * 77))
36+
}
37+
38+
39+
main()

chapters/euclidean_algorithm/euclidean.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ The algorithm is a simple way to find the *greatest common divisor* (GCD) of two
2727
[import:9-17, lang="ocaml"](code/ocaml/euclidean_example.ml)
2828
{% sample lang="go" %}
2929
[import:25-38, lang="golang"](code/go/euclidean.go)
30+
{% sample lang="swift" %}
31+
[import:1-15, lang="swift"](code/swift/euclidean_algorithm.swift)
3032
{% endmethod %}
3133

3234
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:
@@ -60,6 +62,8 @@ Modern implementations, though, often use the modulus operator (%) like so
6062
[import:3-7, lang="ocaml"](code/ocaml/euclidean_example.ml)
6163
{% sample lang="go" %}
6264
[import:14-23, lang="golang"](code/go/euclidean.go)
65+
{% sample lang="swift" %}
66+
[import:17-29, lang="swift"](code/swift/euclidean_algorithm.swift)
6367
{% endmethod %}
6468

6569
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:
@@ -112,6 +116,9 @@ MainClass.java
112116
{% sample lang="go" %}
113117
### Go
114118
[import, lang="golang"](code/go/euclidean.go)
119+
{% sample lang="swift" %}
120+
### Swift
121+
[import, lang="swift"](code/swift/euclidean_algorithm.swift)
115122
{% endmethod %}
116123

117124

0 commit comments

Comments
 (0)