2
2
3
3
import Foundation
4
4
5
- infix operator ^^ { associativity left precedence 160 }
5
+ precedencegroup ExponentiativePrecedence {
6
+ higherThan : MultiplicationPrecedence
7
+ lowerThan : BitwiseShiftPrecedence
8
+ associativity : left
9
+ }
10
+
11
+ infix operator ^^ : ExponentiativePrecedence
6
12
func ^^ ( radix: Int , power: Int ) -> Int {
7
13
return Int ( pow ( Double ( radix) , Double ( power) ) )
8
14
}
9
15
10
16
// Long Multiplication - O(n^2)
11
- func multiply( num1: Int , _ num2: Int , base: Int = 10 ) -> Int {
12
- let num1Array = String ( num1) . characters. reverse ( ) . map { Int ( String ( $0) ) ! }
13
- let num2Array = String ( num2) . characters. reverse ( ) . map { Int ( String ( $0) ) ! }
17
+ func multiply( _ num1: Int , by num2: Int , base: Int = 10 ) -> Int {
18
+ let num1Array = String ( num1) . characters. reversed ( ) . map { Int ( String ( $0) ) ! }
19
+ let num2Array = String ( num2) . characters. reversed ( ) . map { Int ( String ( $0) ) ! }
14
20
15
- var product = Array ( count: num1Array. count + num2Array. count, repeatedValue : 0 )
21
+ var product = Array ( repeating : 0 , count: num1Array. count + num2Array. count)
16
22
17
23
for i in num1Array. indices {
18
24
var carry = 0
@@ -24,16 +30,16 @@ func multiply(num1: Int, _ num2: Int, base: Int = 10) -> Int {
24
30
product [ i + num2Array. count] += carry
25
31
}
26
32
27
- return Int ( product. reverse ( ) . map { String ( $0) } . reduce ( " " , combine : + ) ) !
33
+ return Int ( product. reversed ( ) . map { String ( $0) } . reduce ( " " , + ) ) !
28
34
}
29
35
30
36
// Karatsuba Multiplication - O(nlogn)
31
- func karatsuba( num1: Int , _ num2: Int ) -> Int {
37
+ func karatsuba( _ num1: Int , by num2: Int ) -> Int {
32
38
let num1Array = String ( num1) . characters
33
39
let num2Array = String ( num2) . characters
34
40
35
41
guard num1Array. count > 1 && num2Array. count > 1 else {
36
- return multiply ( num1, num2)
42
+ return multiply ( num1, by : num2)
37
43
}
38
44
39
45
let n = max ( num1Array. count, num2Array. count)
@@ -44,14 +50,12 @@ func karatsuba(num1: Int, _ num2: Int) -> Int {
44
50
let c = num2 / 10 ^^ nBy2
45
51
let d = num2 % 10 ^^ nBy2
46
52
47
- let ac = karatsuba ( a, c)
48
- let bd = karatsuba ( b, d)
49
- let adPluscd = karatsuba ( a+ b, c+ d) - ac - bd
53
+ let ac = karatsuba ( a, by : c)
54
+ let bd = karatsuba ( b, by : d)
55
+ let adPluscd = karatsuba ( a+ b, by : c+ d) - ac - bd
50
56
51
57
let product = ac * 10 ^^ ( 2 * nBy2) + adPluscd * 10 ^^ nBy2 + bd
52
58
53
59
return product
54
60
}
55
61
56
- print ( multiply ( 236742342 , 1231234224 ) )
57
- print ( karatsuba ( 236742342 , 1231234224 ) )
0 commit comments