1
1
//: Playground - noun: a place where people can play
2
2
3
3
import Foundation
4
-
4
+ // last checked with Xcode 9.0b4
5
+ #if swift(>=4.0)
6
+ print ( " Hello, Swift 4 " )
7
+ #endif
5
8
precedencegroup ExponentiativePrecedence {
6
9
higherThan : MultiplicationPrecedence
7
10
lowerThan : BitwiseShiftPrecedence
@@ -17,9 +20,9 @@ func ^^ (radix: Int, power: Int) -> Int {
17
20
func multiply( _ num1: Int , by num2: Int , base: Int = 10 ) -> Int {
18
21
let num1Array = String ( num1) . characters. reversed ( ) . map { Int ( String ( $0) ) ! }
19
22
let num2Array = String ( num2) . characters. reversed ( ) . map { Int ( String ( $0) ) ! }
20
-
23
+
21
24
var product = Array ( repeating: 0 , count: num1Array. count + num2Array. count)
22
-
25
+
23
26
for i in num1Array. indices {
24
27
var carry = 0
25
28
for j in num2Array. indices {
@@ -29,32 +32,32 @@ func multiply(_ num1: Int, by num2: Int, base: Int = 10) -> Int {
29
32
}
30
33
product [ i + num2Array. count] += carry
31
34
}
32
-
35
+
33
36
return Int ( product. reversed ( ) . map { String ( $0) } . reduce ( " " , + ) ) !
34
37
}
35
38
36
39
// Karatsuba Multiplication - O(n^log2(3))
37
40
func karatsuba( _ num1: Int , by num2: Int ) -> Int {
38
41
let num1Array = String ( num1) . characters
39
42
let num2Array = String ( num2) . characters
40
-
43
+
41
44
guard num1Array. count > 1 && num2Array. count > 1 else {
42
45
return multiply ( num1, by: num2)
43
46
}
44
-
47
+
45
48
let n = max ( num1Array. count, num2Array. count)
46
49
let nBy2 = n / 2
47
-
50
+
48
51
let a = num1 / 10 ^^ nBy2
49
52
let b = num1 % 10 ^^ nBy2
50
53
let c = num2 / 10 ^^ nBy2
51
54
let d = num2 % 10 ^^ nBy2
52
-
55
+
53
56
let ac = karatsuba ( a, by: c)
54
57
let bd = karatsuba ( b, by: d)
55
58
let adPlusbc = karatsuba ( a+ b, by: c+ d) - ac - bd
56
-
59
+
57
60
let product = ac * 10 ^^ ( 2 * nBy2) + adPlusbc * 10 ^^ nBy2 + bd
58
-
61
+
59
62
return product
60
63
}
0 commit comments