Skip to content

Commit 2be2228

Browse files
committed
Fix integer overflow in LCM algorithm
1 parent f85748e commit 2be2228

File tree

3 files changed

+3
-3
lines changed

3 files changed

+3
-3
lines changed

GCD/GCD.playground/Contents.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ func gcd(m: Int, _ n: Int) -> Int {
3232
*/
3333

3434
func lcm(_ m: Int, _ n: Int) -> Int {
35-
return m*n / gcd(m, n)
35+
return m / gcd(m, n) * n // we divide before multiplying to avoid integer overflow
3636
}
3737

3838
gcd(52, 39) // 13

GCD/GCD.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,5 +30,5 @@ func gcd(_ a: Int, _ b: Int) -> Int {
3030
Returns the least common multiple of two numbers.
3131
*/
3232
func lcm(_ m: Int, _ n: Int) -> Int {
33-
return m*n / gcd(m, n)
33+
return m / gcd(m, n) * n
3434
}

GCD/README.markdown

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ In code:
102102

103103
```swift
104104
func lcm(_ m: Int, _ n: Int) -> Int {
105-
return m*n / gcd(m, n)
105+
return m / gcd(m, n) * n
106106
}
107107
```
108108

0 commit comments

Comments
 (0)