Skip to content

Commit b4d9f46

Browse files
Wesley-Arringtonjiegillet
authored andcommitted
Improving Euclidean Algorithm in Swift (algorithm-archivists#303)
* Cosmetic changes to Euclidean Algorithm in Swift
1 parent 71557fe commit b4d9f46

File tree

2 files changed

+16
-21
lines changed

2 files changed

+16
-21
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,34 @@
11
func euclidSub(a: Int, b: Int) -> Int {
2-
var A = abs(a)
3-
var B = abs(b)
2+
var a = abs(a)
3+
var b = abs(b)
44

5-
while (A != B) {
6-
if (A > B) {
7-
A -= B
5+
while (a != b) {
6+
if (a > b) {
7+
a -= b
88
} else {
9-
B -= A
9+
b -= a
1010
}
1111
}
1212

13-
return A
13+
return a
1414
}
1515

16-
1716
func euclidMod(a: Int, b: Int) -> Int {
18-
var A = abs(a);
19-
var B = abs(b);
17+
var a = abs(a);
18+
var b = abs(b);
2019

21-
while (B != 0) {
22-
let temp = B
23-
B = A % B
24-
A = temp
20+
while (b != 0) {
21+
let temp = b
22+
b = a % b
23+
a = temp
2524
}
2625

27-
return A
26+
return a
2827
}
2928

30-
31-
32-
3329
func main() {
3430
print(euclidMod(a: 64 * 67, b: 64 * 81))
3531
print(euclidSub(a: 128 * 12, b: 128 * 77))
3632
}
3733

38-
3934
main()

contents/euclidean_algorithm/euclidean_algorithm.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ The algorithm is a simple way to find the *greatest common divisor* (GCD) of two
2828
{% sample lang="go" %}
2929
[import:25-38, lang="golang"](code/go/euclidean.go)
3030
{% sample lang="swift" %}
31-
[import:1-15, lang="swift"](code/swift/euclidean_algorithm.swift)
31+
[import:1-14, lang="swift"](code/swift/euclidean_algorithm.swift)
3232
{% sample lang="matlab" %}
3333
[import:3-17, lang="matlab"](code/matlab/euclidean.m)
3434
{% endmethod %}
@@ -65,7 +65,7 @@ Modern implementations, though, often use the modulus operator (%) like so
6565
{% sample lang="go" %}
6666
[import:14-23, lang="golang"](code/go/euclidean.go)
6767
{% sample lang="swift" %}
68-
[import:17-29, lang="swift"](code/swift/euclidean_algorithm.swift)
68+
[import:16-27, lang="swift"](code/swift/euclidean_algorithm.swift)
6969
{% sample lang="matlab" %}
7070
[import:19-31, lang="matlab"](code/matlab/euclidean.m)
7171
{% endmethod %}

0 commit comments

Comments
 (0)