-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathInteger.swift
662 lines (583 loc) · 17.5 KB
/
Integer.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
//
// Integer.swift
// NumberKit
//
// Created by Matthias Zenger on 11/04/2024.
// Copyright © 2024 Matthias Zenger. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,x either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
/// `Integer` implements signed, arbitrary-size integers. As opposed to `BigInt`,
/// the representation of `Integer` numbers falls back to `Int64` when possible,
/// minimizing memory overhead and increasing the performance of arithmetic operations.
/// `Integer` supports `StaticBigInt`literals, i.e. is is possible to use arbitrary
/// length integer literals.
public enum Integer: IntegerNumber,
SignedInteger,
Hashable,
Codable,
Sendable,
CustomStringConvertible,
CustomDebugStringConvertible {
case int(Int64)
case bigInt(BigInt)
public static var zero: Integer {
return .int(0)
}
public static var one: Integer {
return .int(1)
}
public static var two: Integer {
return .int(2)
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let intNum = try? container.decode(Int64.self) {
self = .int(intNum)
} else if let bigIntNum = try? container.decode(BigInt.self) {
self = .bigInt(bigIntNum)
} else {
throw DecodingError.dataCorrupted(
DecodingError.Context(codingPath: decoder.codingPath,
debugDescription: "Invalid Integer encoding"))
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .int(let num):
try container.encode(num)
case .bigInt(let num):
try container.encode(num)
}
}
public var description: String {
switch self {
case .int(let num):
return num.description
case .bigInt(let num):
return num.description
}
}
public var debugDescription: String {
switch self {
case .int(let num):
return num.description
case .bigInt(let num):
return num.debugDescription
}
}
public var isBigInt: Bool {
guard case .bigInt(_) = self else {
return false
}
return true
}
public var doubleValue: Double {
switch self {
case .int(let num):
return num.doubleValue
case .bigInt(let num):
return num.doubleValue
}
}
public var isOdd: Bool {
switch self {
case .int(let num):
return num.isOdd
case .bigInt(let num):
return num.isOdd
}
}
public init(_ value: Int64) {
self = .int(value)
}
public init(_ value: BigInt) {
if let intNum = value.intValue {
self = .int(intNum)
} else {
self = .bigInt(value)
}
}
public init(_ value: Double) {
let bigIntNum = BigInt(value)
if let intNum = bigIntNum.intValue {
self = .int(intNum)
} else {
self = .bigInt(bigIntNum)
}
}
public init<T: BinaryInteger>(_ source: T) {
if let value = Int64(exactly: source) {
self = .int(value)
} else {
self = Integer(BigInt(source))
}
}
public init?<T: BinaryInteger>(exactly: T) {
self.init(exactly)
}
public init<T: BinaryInteger>(clamping: T) {
self.init(clamping)
}
public init<T: BinaryInteger>(truncatingIfNeeded: T) {
self.init(truncatingIfNeeded)
}
public init<T: BinaryFloatingPoint>(_ source: T) {
if let intNum = Int64(exactly: source) {
self = .int(intNum)
} else if let bigIntNum = BigInt(exactly: source) {
self = .bigInt(bigIntNum)
} else {
self = .int(Int64(source))
}
}
public init?<T: BinaryFloatingPoint>(exactly source: T) {
if let intNum = Int64(exactly: source) {
self = .int(intNum)
} else if let bigIntNum = BigInt(exactly: source) {
self = .bigInt(bigIntNum)
} else {
return nil
}
}
public var intValue: Int64? {
switch self {
case .int(let num):
return num
case .bigInt(_):
return nil
}
}
public var bigIntValue: BigInt {
switch self {
case .int(let num):
return BigInt(num)
case .bigInt(let num):
return num
}
}
public var words: [UInt] {
switch self {
case .int(let num):
return BigInt(num).words
case .bigInt(let num):
return num.words
}
}
public var magnitude: Integer {
switch self {
case .int(let num):
return Integer(BigInt(num.magnitude))
case .bigInt(let num):
return Integer(num.magnitude)
}
}
public var bitWidth: Int {
switch self {
case .int(let num):
return num.bitWidth
case .bigInt(let num):
return num.bitWidth
}
}
public var trailingZeroBitCount: Int {
switch self {
case .int(let num):
return num.trailingZeroBitCount
case .bigInt(let num):
return num.trailingZeroBitCount
}
}
public var isNegative: Bool {
switch self {
case .int(let num):
return num < 0
case .bigInt(let num):
return num.isNegative
}
}
public var isZero: Bool {
switch self {
case .int(let num):
return num == 0
case .bigInt(let num):
return num.isZero
}
}
public var negate: Integer {
switch self {
case .int(let num):
if num == .min {
return Integer(BigInt(num).negate)
} else {
return .int(-num)
}
case .bigInt(let num):
return Integer(BigInt(num).negate)
}
}
public var abs: Integer {
switch self {
case .int(let num):
if num == .min {
return .bigInt(BigInt(num).abs)
} else {
return .int(Swift.abs(num))
}
case .bigInt(let num):
return Integer(num.abs)
}
}
public func divided(by rhs: Integer) -> (quotient: Integer, remainder: Integer) {
let (q, r) = self.bigIntValue.divided(by: rhs.bigIntValue)
return (Integer(q), Integer(r))
}
public func toPower(of exp: Integer) -> Integer {
return Integer(self.bigIntValue.toPower(of: exp.bigIntValue))
}
public var sqrt: Integer {
return Integer(self.bigIntValue.sqrt)
}
/// Adds `n` and returns the result.
public func advanced(by n: Integer) -> Integer {
return self + n
}
/// Computes the distance to `other` and returns the result.
public func distance(to other: Integer) -> Integer {
return other - self
}
/// Returns -1 if `self` is less than `rhs`,
/// 0 if `self` is equals to `rhs`,
/// +1 if `self` is greater than `rhs`
public func compare(to rhs: Integer) -> Int {
switch self {
case .int(let lval):
switch rhs {
case .int(let rval):
return lval == rval ? 0 : lval < rval ? -1 : 1
case .bigInt(let rval):
return BigInt(lval).compare(to: rval)
}
case .bigInt(let lval):
switch rhs {
case .int(let rval):
return lval.compare(to: BigInt(rval))
case .bigInt(let rval):
return lval.compare(to: rval)
}
}
}
/// Number of bits used to represent the (unsigned) `Integer` number.
public var bitSize: Int {
return self.bigIntValue.bitSize
}
/// Number of bits set in this `Integer` number. For negative numbers, `n.bigCount` returns
/// `~n.not.bigCount`.
public var bitCount: Int {
return self.bigIntValue.bitCount
}
/// Returns a random non-negative `Integer` with up to `bitWidth` bits using the random number
/// generator `generator`.
public static func random<R: RandomNumberGenerator>(withMaxBits bitWidth: Int,
using generator: inout R) -> Integer {
return Integer(BigInt.random(withMaxBits: bitWidth, using: &generator))
}
/// Returns a random non-negative `Integer` with up to `bitWidth` bits using the system
/// random number generator.
public static func random(withMaxBits bitWidth: Int) -> Integer {
return Integer(BigInt.random(withMaxBits: bitWidth))
}
/// Returns a random non-negative `Integer` below the given upper bound `bound` using the
/// random number generator `generator`.
public static func random<R: RandomNumberGenerator>(below bound: Integer,
using generator: inout R) -> Integer {
return Integer(BigInt.random(below: bound.bigIntValue, using: &generator))
}
/// Returns a random non-negative `Integer` below the given upper bound `bound` using
/// the system random number generator.
public static func random(below bound: Integer) -> Integer {
return Integer(BigInt.random(below: bound.bigIntValue))
}
public static prefix func -(x: Integer) -> Integer {
return x.negate
}
public static prefix func ~(x: Integer) -> Integer {
switch x {
case .int(let num):
return .int(~num)
case .bigInt(let num):
return .bigInt(~num)
}
}
public static func +(lhs: Integer, rhs: Integer) -> Integer {
switch lhs {
case .int(let lval):
switch rhs {
case .int(let rval):
let (res, overflow) = lval.addingReportingOverflow(rval)
if overflow {
return .bigInt(BigInt(lval) + BigInt(rval))
} else {
return .int(res)
}
case .bigInt(let rval):
return Integer(BigInt(lval) + rval)
}
case .bigInt(let lval):
switch rhs {
case .int(let rval):
return Integer(lval + BigInt(rval))
case .bigInt(let rval):
return Integer(lval + rval)
}
}
}
public static func -(lhs: Integer, rhs: Integer) -> Integer {
switch lhs {
case .int(let lval):
switch rhs {
case .int(let rval):
let (res, overflow) = lval.subtractingReportingOverflow(rval)
if overflow {
return Integer(BigInt(lval) - BigInt(rval))
} else {
return .int(res)
}
case .bigInt(let rval):
return Integer(BigInt(lval) - rval)
}
case .bigInt(let lval):
switch rhs {
case .int(let rval):
return Integer(lval - BigInt(rval))
case .bigInt(let rval):
return Integer(lval - rval)
}
}
}
public static func *(lhs: Integer, rhs: Integer) -> Integer {
switch lhs {
case .int(let lval):
switch rhs {
case .int(let rval):
let (res, overflow) = lval.multipliedReportingOverflow(by: rval)
if overflow {
return Integer(BigInt(lval) * BigInt(rval))
} else {
return .int(res)
}
case .bigInt(let rval):
return Integer(BigInt(lval) * rval)
}
case .bigInt(let lval):
switch rhs {
case .int(let rval):
return Integer(lval * BigInt(rval))
case .bigInt(let rval):
return Integer(lval * rval)
}
}
}
public static func /(lhs: Integer, rhs: Integer) -> Integer {
switch lhs {
case .int(let lval):
switch rhs {
case .int(let rval):
let (res, overflow) = lval.dividedReportingOverflow(by: rval)
if overflow {
return Integer(BigInt(lval) / BigInt(rval))
} else {
return .int(res)
}
case .bigInt(let rval):
return Integer(BigInt(lval) / rval)
}
case .bigInt(let lval):
switch rhs {
case .int(let rval):
return Integer(lval / BigInt(rval))
case .bigInt(let rval):
return Integer(lval / rval)
}
}
}
public static func %(lhs: Integer, rhs: Integer) -> Integer {
switch lhs {
case .int(let lval):
switch rhs {
case .int(let rval):
let (res, overflow) = lval.remainderReportingOverflow(dividingBy: rval)
if overflow {
return Integer(BigInt(lval) % BigInt(rval))
} else {
return .int(res)
}
case .bigInt(let rval):
return Integer(BigInt(lval) % rval)
}
case .bigInt(let lval):
switch rhs {
case .int(let rval):
return Integer(lval % BigInt(rval))
case .bigInt(let rval):
return Integer(lval % rval)
}
}
}
public static func &(lhs: Integer, rhs: Integer) -> Integer {
switch lhs {
case .int(let lval):
switch rhs {
case .int(let rval):
return .int(lval & rval)
case .bigInt(let rval):
return Integer(BigInt(lval) & rval)
}
case .bigInt(let lval):
switch rhs {
case .int(let rval):
return Integer(lval & BigInt(rval))
case .bigInt(let rval):
return Integer(lval & rval)
}
}
}
public static func |(lhs: Integer, rhs: Integer) -> Integer {
switch lhs {
case .int(let lval):
switch rhs {
case .int(let rval):
return .int(lval | rval)
case .bigInt(let rval):
return Integer(BigInt(lval) | rval)
}
case .bigInt(let lval):
switch rhs {
case .int(let rval):
return Integer(lval | BigInt(rval))
case .bigInt(let rval):
return Integer(lval | rval)
}
}
}
public static func ^(lhs: Integer, rhs: Integer) -> Integer {
switch lhs {
case .int(let lval):
switch rhs {
case .int(let rval):
return .int(lval ^ rval)
case .bigInt(let rval):
return Integer(BigInt(lval) ^ rval)
}
case .bigInt(let lval):
switch rhs {
case .int(let rval):
return Integer(lval ^ BigInt(rval))
case .bigInt(let rval):
return Integer(lval ^ rval)
}
}
}
public static func << <T: BinaryInteger>(lhs: Integer, rhs: T) -> Integer {
return Integer(lhs.bigIntValue << rhs)
}
public static func >> <T: BinaryInteger>(lhs: Integer, rhs: T) -> Integer {
return Integer(lhs.bigIntValue >> rhs)
}
public static func +=(lhs: inout Integer, rhs: Integer) {
lhs = lhs + rhs
}
public static func -=(lhs: inout Integer, rhs: Integer) {
lhs = lhs - rhs
}
public static func *=(lhs: inout Integer, rhs: Integer) {
lhs = lhs * rhs
}
public static func /=(lhs: inout Integer, rhs: Integer) {
lhs = lhs / rhs
}
public static func %= (lhs: inout Integer, rhs: Integer) {
lhs = lhs % rhs
}
public static func &= (lhs: inout Integer, rhs: Integer) {
lhs = lhs & rhs
}
public static func |= (lhs: inout Integer, rhs: Integer) {
lhs = lhs | rhs
}
public static func ^=(lhs: inout Integer, rhs: Integer) {
lhs = lhs ^ rhs
}
public static func <<=<T: BinaryInteger>(lhs: inout Integer, rhs: T) {
lhs = lhs << rhs
}
public static func >>=<T: BinaryInteger>(lhs: inout Integer, rhs: T) {
lhs = lhs >> rhs
}
public static func <(lhs: Integer, rhs: Integer) -> Bool {
return lhs.compare(to: rhs) < 0
}
public static func <=(lhs: Integer, rhs: Integer) -> Bool {
return lhs.compare(to: rhs) <= 0
}
public static func >=(lhs: Integer, rhs: Integer) -> Bool {
return lhs.compare(to: rhs) >= 0
}
public static func >(lhs: Integer, rhs: Integer) -> Bool {
return lhs.compare(to: rhs) > 0
}
public static func ==(lhs: Integer, rhs: Integer) -> Bool {
return lhs.compare(to: rhs) == 0
}
public static func !=(lhs: Integer, rhs: Integer) -> Bool {
return lhs.compare(to: rhs) != 0
}
public func addingReportingOverflow(_ rhs: Integer) -> (partialValue: Integer, overflow: Bool) {
return (self + rhs, false)
}
public func subtractingReportingOverflow(_ rhs: Integer) -> (partialValue: Integer, overflow: Bool) {
return (self - rhs, false)
}
public func multipliedReportingOverflow(by rhs: Integer) -> (partialValue: Integer, overflow: Bool) {
return (self * rhs, false)
}
public func dividedReportingOverflow(by rhs: Integer) -> (partialValue: Integer, overflow: Bool) {
return (self / rhs, false)
}
public func remainderReportingOverflow(dividingBy rhs: Integer) -> (partialValue: Integer, overflow: Bool) {
return (self % rhs, false)
}
}
#if canImport(Swift.StaticBigInt)
extension Integer: ExpressibleByIntegerLiteral {
public init(integerLiteral value: StaticBigInt) {
self = Integer(BigInt(integerLiteral: value))
}
}
#else
extension Integer: ExpressibleByIntegerLiteral {
public init(integerLiteral value: Int64) {
self.init(value)
}
}
#endif
/// Returns the maximum of `fst` and `snd`.
public func max(_ fst: Integer, _ snd: Integer) -> Integer {
return fst.compare(to: snd) >= 0 ? fst : snd
}
/// Returns the minimum of `fst` and `snd`.
public func min(_ fst: Integer, _ snd: Integer) -> Integer {
return fst.compare(to: snd) <= 0 ? fst : snd
}