mirror of
https://github.com/apple/swift-numerics
synced 2026-11-22 04:30:45 +00:00
Compare commits
107
Commits
1.1.0
...
biginteger
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0098c438eb | ||
|
|
349fdf1e01 | ||
|
|
0d48ff5a98 | ||
|
|
1c90bdc9a9 | ||
|
|
fd9722e609 | ||
|
|
f11ce9b248 | ||
|
|
935eac199c | ||
|
|
2f60891517 | ||
|
|
5ea7711e02 | ||
|
|
b74c1ce133 | ||
|
|
cd88f161eb | ||
|
|
aaeb9029e9 | ||
|
|
52e7e70caf | ||
|
|
caeeaaa9dd | ||
|
|
cc5f7e5d18 | ||
|
|
feeac39506 | ||
|
|
19951768df | ||
|
|
87900161d6 | ||
|
|
6e0f0094dc | ||
|
|
7d6e5cda3e | ||
|
|
e4f5257d0a | ||
|
|
9e1a1f5e8a | ||
|
|
7026eb4085 | ||
|
|
1a29830c82 | ||
|
|
5919d3f48f | ||
|
|
e3d01dd680 | ||
|
|
90d5ddd1f6 | ||
|
|
e41c631052 | ||
|
|
6e85aa2bbd | ||
|
|
ceee280ebe | ||
|
|
3501fa7c61 | ||
|
|
ca75d2d124 | ||
|
|
ffdaf86868 | ||
|
|
bf9afea2eb | ||
|
|
4c425513cd | ||
|
|
fc7b3bf44f | ||
|
|
0dee6d0927 | ||
|
|
cfc63e8adc | ||
|
|
01c30961ef | ||
|
|
05a45984d9 | ||
|
|
cfc2cd7c97 | ||
|
|
98023c3575 | ||
|
|
506ea36331 | ||
|
|
1b733de54a | ||
|
|
937c292898 | ||
|
|
49121f353a | ||
|
|
e632de88c4 | ||
|
|
b03af80076 | ||
|
|
6f4374cd99 | ||
|
|
d36d9ce02e | ||
|
|
fac716fdb2 | ||
|
|
7ca51a3e50 | ||
|
|
1ddbbfe0d1 | ||
|
|
eab5a94499 | ||
|
|
a6ecb7442a | ||
|
|
2410717a17 | ||
|
|
7ae61f775b | ||
|
|
fe212356fd | ||
|
|
830927ecbb | ||
|
|
fd8049e481 | ||
|
|
0b121fd774 | ||
|
|
72f1cb3554 | ||
|
|
0e58379b4f | ||
|
|
ddaf8be1a2 | ||
|
|
9ddc664ef1 | ||
|
|
b39dd05db3 | ||
|
|
1cb69383a5 | ||
|
|
c9d72fc3ae | ||
|
|
4ec520a726 | ||
|
|
8c378528de | ||
|
|
3cf0b0cf74 | ||
|
|
f6a3d2d4e4 | ||
|
|
036ab5fe94 | ||
|
|
7c6e2ce0d8 | ||
|
|
3a4cc1c623 | ||
|
|
4d7e4e9b97 | ||
|
|
3c916262e0 | ||
|
|
831f06ac78 | ||
|
|
d15400e6ab | ||
|
|
5be3b4e526 | ||
|
|
acd8568864 | ||
|
|
11d5225f3b | ||
|
|
19d3491df4 | ||
|
|
819ebd90c4 | ||
|
|
5b84051f2a | ||
|
|
cb5e7f3c7a | ||
|
|
5cb9b95ce8 | ||
|
|
5db4a69e57 | ||
|
|
2419741a7c | ||
|
|
368caf5b3f | ||
|
|
a799618103 | ||
|
|
dbf743b314 | ||
|
|
2f40de6195 | ||
|
|
38073d2ab5 | ||
|
|
2863c44182 | ||
|
|
e490f1fc66 | ||
|
|
67858690eb | ||
|
|
cced27a6c0 | ||
|
|
821fcbd6a4 | ||
|
|
b46dcf96c6 | ||
|
|
eceae6d7bd | ||
|
|
ac50a90a60 | ||
|
|
524dc69ae1 | ||
|
|
ea2b6f8deb | ||
|
|
cb56525312 | ||
|
|
bc2f9fb7c6 | ||
|
|
96d41bcf9f |
No files matched your search
@@ -1,4 +1,4 @@
|
||||
version: 1
|
||||
builder:
|
||||
configs:
|
||||
- documentation_targets: [Numerics, RealModule, ComplexModule]
|
||||
- documentation_targets: [Numerics, RealModule, ComplexModule, BigIntModule]
|
||||
+13
-1
@@ -18,6 +18,7 @@ let package = Package(
|
||||
|
||||
name: "swift-numerics",
|
||||
products: [
|
||||
.library(name: "BigIntModule", targets: ["BigIntModule"]),
|
||||
.library(name: "ComplexModule", targets: ["ComplexModule"]),
|
||||
.library(name: "Numerics", targets: ["Numerics"]),
|
||||
.library(name: "RealModule", targets: ["RealModule"]),
|
||||
@@ -25,6 +26,12 @@ let package = Package(
|
||||
|
||||
targets: [
|
||||
// MARK: - Public API
|
||||
.target(
|
||||
name: "BigIntModule",
|
||||
dependencies: [],
|
||||
exclude: excludedFilenames
|
||||
),
|
||||
|
||||
.target(
|
||||
name: "ComplexModule",
|
||||
dependencies: ["RealModule"],
|
||||
@@ -39,7 +46,7 @@ let package = Package(
|
||||
|
||||
.target(
|
||||
name: "Numerics",
|
||||
dependencies: ["ComplexModule", "IntegerUtilities", "RealModule"],
|
||||
dependencies: ["ComplexModule", "IntegerUtilities", "RealModule", "BigIntModule"],
|
||||
exclude: excludedFilenames
|
||||
),
|
||||
|
||||
@@ -65,6 +72,11 @@ let package = Package(
|
||||
),
|
||||
|
||||
// MARK: - Unit test bundles
|
||||
.testTarget(
|
||||
name: "BigIntTests",
|
||||
dependencies: ["BigIntModule"]
|
||||
),
|
||||
|
||||
.testTarget(
|
||||
name: "ComplexTests",
|
||||
dependencies: ["_TestSupport"],
|
||||
|
||||
+13
-1
@@ -18,6 +18,7 @@ let package = Package(
|
||||
|
||||
name: "swift-numerics",
|
||||
products: [
|
||||
.library(name: "BigIntModule", targets: ["BigIntModule"]),
|
||||
.library(name: "ComplexModule", targets: ["ComplexModule"]),
|
||||
.library(name: "Numerics", targets: ["Numerics"]),
|
||||
.library(name: "RealModule", targets: ["RealModule"]),
|
||||
@@ -25,6 +26,12 @@ let package = Package(
|
||||
|
||||
targets: [
|
||||
// MARK: - Public API
|
||||
.target(
|
||||
name: "BigIntModule",
|
||||
dependencies: [],
|
||||
exclude: excludedFilenames
|
||||
),
|
||||
|
||||
.target(
|
||||
name: "ComplexModule",
|
||||
dependencies: ["RealModule"],
|
||||
@@ -39,7 +46,7 @@ let package = Package(
|
||||
|
||||
.target(
|
||||
name: "Numerics",
|
||||
dependencies: ["ComplexModule", "IntegerUtilities", "RealModule"],
|
||||
dependencies: ["ComplexModule", "IntegerUtilities", "RealModule", "BigIntModule"],
|
||||
exclude: excludedFilenames
|
||||
),
|
||||
|
||||
@@ -65,6 +72,11 @@ let package = Package(
|
||||
),
|
||||
|
||||
// MARK: - Unit test bundles
|
||||
.testTarget(
|
||||
name: "BigIntTests",
|
||||
dependencies: ["BigIntModule"]
|
||||
),
|
||||
|
||||
.testTarget(
|
||||
name: "ComplexTests",
|
||||
dependencies: ["_TestSupport"],
|
||||
|
||||
@@ -106,6 +106,7 @@ Questions about how to use Swift Numerics modules, or issues that are not clearl
|
||||
1. [`RealModule`](Sources/RealModule/README.md)
|
||||
2. [`ComplexModule`](Sources/ComplexModule/README.md)
|
||||
3. [`IntegerUtilities`](Sources/IntegerUtilities/README.md) (on main only, not yet present in a released tag)
|
||||
4. [`BigIntModule`](Sources/BigIntModule/README.md) (on branch only)
|
||||
|
||||
## Future expansion
|
||||
|
||||
|
||||
@@ -0,0 +1,810 @@
|
||||
//===--- BigInt.swift -----------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019 - 2020 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
public struct BigInt: SignedInteger {
|
||||
|
||||
public typealias Words = [UInt]
|
||||
|
||||
public private(set) var words: Words
|
||||
|
||||
@usableFromInline
|
||||
internal init(_uncheckedWords: Words) {
|
||||
self.words = _uncheckedWords
|
||||
}
|
||||
|
||||
public init<T>(bitPattern source: T) where T: BinaryInteger {
|
||||
words = Words(source.words)
|
||||
BigInt._dropExcessWords(words: &words)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal var _isNegative: Bool {
|
||||
words[words.endIndex - 1] > Int.max
|
||||
}
|
||||
|
||||
private static let _digits: [BigInt] = (0 ... 36).map {
|
||||
BigInt(_uncheckedWords: [UInt(bitPattern: $0)])
|
||||
}
|
||||
|
||||
private static let _digitRadix = BigInt(_uncheckedWords: [0, 1])
|
||||
}
|
||||
|
||||
// MARK: - Basic Behaviors
|
||||
|
||||
extension BigInt: Equatable {
|
||||
|
||||
@inlinable
|
||||
public static func == (lhs: BigInt, rhs: BigInt) -> Bool {
|
||||
lhs.words == rhs.words
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func != (lhs: BigInt, rhs: BigInt) -> Bool {
|
||||
!(lhs == rhs)
|
||||
}
|
||||
}
|
||||
|
||||
extension BigInt: Hashable {
|
||||
|
||||
@inlinable
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(words)
|
||||
}
|
||||
}
|
||||
|
||||
extension BigInt: Comparable {
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: BigInt, rhs: BigInt) -> Bool {
|
||||
let lhsNegative = lhs._isNegative
|
||||
let rhsNegative = rhs._isNegative
|
||||
|
||||
if lhsNegative && !rhsNegative { return true }
|
||||
if rhsNegative && !lhsNegative { return false }
|
||||
|
||||
if (lhsNegative && rhsNegative) || (!lhsNegative && !rhsNegative) {
|
||||
if lhs.words.count > rhs.words.count {
|
||||
return lhsNegative ? true : false
|
||||
}
|
||||
if lhs.words.count < rhs.words.count {
|
||||
return lhsNegative ? false : true
|
||||
}
|
||||
|
||||
for i in stride(from: lhs.words.count - 1, through: 0, by: -1) {
|
||||
if lhs.words[i] > rhs.words[i] {
|
||||
return false
|
||||
} else if lhs.words[i] < rhs.words[i] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
extension BigInt: LosslessStringConvertible {
|
||||
|
||||
public init?(_ description: String) {
|
||||
self.init(description, radix: 10)
|
||||
}
|
||||
|
||||
public init?<T>(_ description: T, radix: Int = 10) where T: StringProtocol {
|
||||
precondition(2 ... 36 ~= radix, "Radix not in range 2 ... 36")
|
||||
|
||||
self = 0
|
||||
|
||||
let isNegative = description.hasPrefix("-")
|
||||
let hasPrefix = isNegative || description.hasPrefix("+")
|
||||
let utf8 = description.utf8.dropFirst(hasPrefix ? 1 : 0)
|
||||
guard !utf8.isEmpty else { return nil }
|
||||
|
||||
for var byte in utf8 {
|
||||
switch byte {
|
||||
case UInt8(ascii: "0") ... UInt8(ascii: "9"):
|
||||
byte -= UInt8(ascii: "0")
|
||||
case UInt8(ascii: "A") ... UInt8(ascii: "Z"):
|
||||
byte -= UInt8(ascii: "A")
|
||||
byte += 10
|
||||
case UInt8(ascii: "a") ... UInt8(ascii: "z"):
|
||||
byte -= UInt8(ascii: "a")
|
||||
byte += 10
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
guard byte < radix else { return nil }
|
||||
self *= BigInt._digits[radix]
|
||||
self += BigInt._digits[Int(byte)]
|
||||
}
|
||||
|
||||
if isNegative {
|
||||
self.negate()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension BigInt: Decodable {
|
||||
|
||||
public init(from decoder: Decoder) throws {
|
||||
let singleValueContainer = try decoder.singleValueContainer()
|
||||
let description = try singleValueContainer.decode(String.self)
|
||||
guard let result = BigInt(description) else {
|
||||
throw DecodingError.dataCorruptedError(
|
||||
in: singleValueContainer,
|
||||
debugDescription: "BigInt(\(description.debugDescription)) failed")
|
||||
}
|
||||
self = result
|
||||
}
|
||||
}
|
||||
|
||||
extension BigInt: Encodable {
|
||||
|
||||
public func encode(to encoder: Encoder) throws {
|
||||
var singleValueContainer = encoder.singleValueContainer()
|
||||
try singleValueContainer.encode(description)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Numeric Protocols
|
||||
|
||||
extension BigInt: ExpressibleByIntegerLiteral {
|
||||
|
||||
public init(integerLiteral value: Int) {
|
||||
if value >= 0, value < BigInt._digits.count {
|
||||
self = BigInt._digits[value]
|
||||
} else {
|
||||
words = [UInt(bitPattern: value)]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension BigInt: AdditiveArithmetic {
|
||||
|
||||
@inlinable
|
||||
public static func + (lhs: BigInt, rhs: BigInt) -> BigInt {
|
||||
var result = lhs
|
||||
result += rhs
|
||||
return result
|
||||
}
|
||||
|
||||
public static func += (lhs: inout BigInt, rhs: BigInt) {
|
||||
if lhs.words.count == 1, rhs.words.count == 1 {
|
||||
let lhsWord = lhs.words[0]
|
||||
let rhsWord = rhs.words[0]
|
||||
|
||||
let (result, isOverflow) = lhsWord.addingReportingOverflow(rhsWord)
|
||||
|
||||
if !isOverflow && result < Int.max {
|
||||
lhs.words[0] = result
|
||||
return
|
||||
}
|
||||
let knownNegativeResult = lhsWord > Int.max && rhsWord > Int.max
|
||||
|
||||
if lhsWord > Int.max || rhsWord > Int.max, !knownNegativeResult {
|
||||
// positive + negative is always smaller, so overflow is a red herring
|
||||
lhs.words[0] = result
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var isOverflow = false
|
||||
|
||||
var rhsWords = rhs.words
|
||||
|
||||
lhs.words.append(lhs._isNegative ? UInt.max : 0)
|
||||
rhsWords.append(rhs._isNegative ? UInt.max : 0)
|
||||
|
||||
BigInt._signExtend(lhsWords: &lhs.words, rhsWords: &rhsWords)
|
||||
var temp: UInt = 0
|
||||
for index in 0 ..< lhs.words.count {
|
||||
var carryOverflow = false
|
||||
|
||||
if isOverflow {
|
||||
(temp, carryOverflow) = rhsWords[index].addingReportingOverflow(1)
|
||||
} else {
|
||||
temp = rhsWords[index]
|
||||
}
|
||||
|
||||
(lhs.words[index], isOverflow) = lhs.words[index].addingReportingOverflow(temp)
|
||||
|
||||
isOverflow = carryOverflow || isOverflow
|
||||
}
|
||||
|
||||
BigInt._dropExcessWords(words: &lhs.words)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func - (lhs: BigInt, rhs: BigInt) -> BigInt {
|
||||
var result = lhs
|
||||
result -= rhs
|
||||
return result
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func -= (lhs: inout BigInt, rhs: BigInt) {
|
||||
lhs += -rhs
|
||||
}
|
||||
}
|
||||
|
||||
extension BigInt: Numeric {
|
||||
|
||||
public init?<T>(exactly source: T) where T: BinaryInteger {
|
||||
self.init(source)
|
||||
}
|
||||
|
||||
public var magnitude: BigInt { _isNegative ? -self : self }
|
||||
|
||||
public static func * (lhs: BigInt, rhs: BigInt) -> BigInt {
|
||||
let lhsIsNeg = lhs.words[lhs.words.endIndex - 1] > Int.max
|
||||
let rhsIsNeg = rhs.words[rhs.words.endIndex - 1] > Int.max
|
||||
|
||||
let lhsWords = lhsIsNeg ? (-lhs).words : lhs.words
|
||||
let rhsWords = rhsIsNeg ? (-rhs).words : rhs.words
|
||||
|
||||
let count = lhsWords.count + rhsWords.count + 1
|
||||
var newWords = Words(repeating: 0, count: count)
|
||||
|
||||
for i in 0 ..< rhsWords.count {
|
||||
var carry: UInt = 0
|
||||
var digit: UInt = 0
|
||||
|
||||
var lastJ: Int = 0
|
||||
for j in i ..< (lhsWords.count + i) {
|
||||
var (high, low) = rhsWords[i].multipliedFullWidth(by: lhsWords[j - i])
|
||||
var isOverflow: Bool
|
||||
(digit, isOverflow) = low.addingReportingOverflow(newWords[j])
|
||||
if isOverflow {
|
||||
high += 1
|
||||
}
|
||||
|
||||
(digit, isOverflow) = digit.addingReportingOverflow(carry)
|
||||
if isOverflow {
|
||||
high += 1
|
||||
}
|
||||
|
||||
carry = high
|
||||
newWords[j] = digit
|
||||
lastJ = j
|
||||
}
|
||||
|
||||
if carry != 0 {
|
||||
let isOverflow: Bool
|
||||
(digit, isOverflow) = newWords[lastJ + 1].addingReportingOverflow(carry)
|
||||
if isOverflow {
|
||||
carry = 1
|
||||
}
|
||||
newWords[lastJ + 1] = digit
|
||||
}
|
||||
}
|
||||
|
||||
for i in stride(from: count - 1, through: 1, by: -1) {
|
||||
if newWords[i] == 0, newWords[i - 1] <= Int.max {
|
||||
newWords.removeLast()
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if lhsIsNeg || rhsIsNeg, !(lhsIsNeg && rhsIsNeg) {
|
||||
return -BigInt(_uncheckedWords: newWords)
|
||||
}
|
||||
|
||||
return BigInt(_uncheckedWords: newWords)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func *= (lhs: inout BigInt, rhs: BigInt) {
|
||||
lhs = lhs * rhs
|
||||
}
|
||||
}
|
||||
|
||||
extension BigInt: SignedNumeric {
|
||||
|
||||
public mutating func negate() {
|
||||
var isOverflow = true
|
||||
for i in 0 ..< words.count {
|
||||
if isOverflow {
|
||||
(words[i], isOverflow) = (~words[i]).addingReportingOverflow(1)
|
||||
} else {
|
||||
words[i] = ~words[i]
|
||||
}
|
||||
}
|
||||
|
||||
BigInt._dropExcessWords(words: &words)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static prefix func - (x: BigInt) -> BigInt {
|
||||
var result = x
|
||||
result.negate()
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
extension BigInt: BinaryInteger {
|
||||
|
||||
public init?<T>(exactly source: T) where T: BinaryFloatingPoint {
|
||||
guard source.isFinite, source == source.rounded(.towardZero) else {
|
||||
return nil
|
||||
}
|
||||
self.init(source)
|
||||
}
|
||||
|
||||
public init<T>(_ source: T) where T: BinaryFloatingPoint {
|
||||
precondition(
|
||||
source.isFinite,
|
||||
"""
|
||||
\(type(of: source)) value cannot be converted to BigInt because it is \
|
||||
either infinite or NaN
|
||||
""")
|
||||
|
||||
let isNegative = source < 0.0
|
||||
var float = isNegative ? -source : source
|
||||
|
||||
if let _ = UInt(exactly: T.greatestFiniteMagnitude) {
|
||||
words = [UInt(float)]
|
||||
} else {
|
||||
var words = Words()
|
||||
let radix = T(sign: .plus, exponent: T.Exponent(UInt.bitWidth), significand: 1)
|
||||
repeat {
|
||||
let digit = UInt(float.truncatingRemainder(dividingBy: radix))
|
||||
words.append(digit)
|
||||
float = (float / radix).rounded(.towardZero)
|
||||
} while float != 0
|
||||
|
||||
if let last = words.last, last >= Int.max {
|
||||
words.append(0)
|
||||
}
|
||||
self.words = words
|
||||
}
|
||||
|
||||
if isNegative {
|
||||
self.negate()
|
||||
}
|
||||
}
|
||||
|
||||
public init<T>(_ source: T) where T: BinaryInteger {
|
||||
if source >= 0, source < BigInt._digits.count {
|
||||
self = BigInt._digits[Int(source)]
|
||||
} else {
|
||||
words = Words(source.words)
|
||||
if source > 0 && source.words[source.words.endIndex - 1] > Int.max {
|
||||
words.append(0)
|
||||
}
|
||||
// needed to handle sign-extended multi-word numbers that
|
||||
// actually fit in a single word
|
||||
BigInt._dropExcessWords(words: &words)
|
||||
}
|
||||
}
|
||||
|
||||
public init<T>(clamping source: T) where T: BinaryInteger {
|
||||
self.init(source)
|
||||
}
|
||||
|
||||
public init<T>(truncatingIfNeeded source: T) where T: BinaryInteger {
|
||||
words = Words(source.words)
|
||||
}
|
||||
|
||||
public var bitWidth: Int { words.count * UInt.bitWidth }
|
||||
|
||||
public var trailingZeroBitCount: Int {
|
||||
var totalZeros = 0
|
||||
for word in words {
|
||||
if word == 0 {
|
||||
totalZeros += UInt.bitWidth
|
||||
} else {
|
||||
totalZeros += word.trailingZeroBitCount
|
||||
break
|
||||
}
|
||||
}
|
||||
return totalZeros
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func / (lhs: BigInt, rhs: BigInt) -> BigInt {
|
||||
let (result, _) = _div(lhs: lhs, rhs: rhs)
|
||||
return result
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func /= (lhs: inout BigInt, rhs: BigInt) {
|
||||
lhs = lhs / rhs
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func % (lhs: BigInt, rhs: BigInt) -> BigInt {
|
||||
let (_, result) = _div(lhs: lhs, rhs: rhs)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func %= (lhs: inout BigInt, rhs: BigInt) {
|
||||
lhs = lhs % rhs
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static prefix func ~ (x: BigInt) -> BigInt {
|
||||
let newWords = x.words.map { ~$0 }
|
||||
return BigInt(_uncheckedWords: Words(newWords))
|
||||
}
|
||||
|
||||
public static func &= (lhs: inout BigInt, rhs: BigInt) {
|
||||
var rhsWords = rhs.words
|
||||
BigInt._signExtend(lhsWords: &lhs.words, rhsWords: &rhsWords)
|
||||
|
||||
for i in 0 ..< rhsWords.count {
|
||||
lhs.words[i] &= rhsWords[i]
|
||||
}
|
||||
|
||||
BigInt._dropExcessWords(words: &lhs.words)
|
||||
}
|
||||
|
||||
public static func |= (lhs: inout BigInt, rhs: BigInt) {
|
||||
var rhsWords = rhs.words
|
||||
BigInt._signExtend(lhsWords: &lhs.words, rhsWords: &rhsWords)
|
||||
|
||||
for i in 0 ..< rhsWords.count {
|
||||
lhs.words[i] |= rhsWords[i]
|
||||
}
|
||||
|
||||
BigInt._dropExcessWords(words: &lhs.words)
|
||||
}
|
||||
|
||||
public static func ^= (lhs: inout BigInt, rhs: BigInt) {
|
||||
var rhsWords = rhs.words
|
||||
BigInt._signExtend(lhsWords: &lhs.words, rhsWords: &rhsWords)
|
||||
|
||||
for i in 0 ..< rhsWords.count {
|
||||
lhs.words[i] &= rhsWords[i]
|
||||
}
|
||||
|
||||
BigInt._dropExcessWords(words: &lhs.words)
|
||||
}
|
||||
|
||||
public static func <<= <RHS>(lhs: inout BigInt, rhs: RHS) where RHS: BinaryInteger {
|
||||
if rhs.signum() < 0 {
|
||||
lhs >>= rhs.magnitude
|
||||
return
|
||||
}
|
||||
|
||||
let wordLength = UInt.bitWidth
|
||||
let isNegative = lhs._isNegative
|
||||
|
||||
let (fullWords, remainder) = rhs.quotientAndRemainder(dividingBy: RHS(wordLength))
|
||||
lhs.words = Words(repeating: 0, count: Int(fullWords)) + lhs.words + [isNegative ? UInt.max : 0]
|
||||
|
||||
if remainder > 0 {
|
||||
var value: UInt = 0
|
||||
for i in 0 ..< lhs.words.count {
|
||||
let temp = lhs.words[i] >> (wordLength - Int(remainder))
|
||||
lhs.words[i] <<= Int(remainder)
|
||||
if i > 0 {
|
||||
lhs.words[i] &= UInt.max << Int(remainder)
|
||||
lhs.words[i] |= value
|
||||
}
|
||||
|
||||
value = temp
|
||||
}
|
||||
|
||||
if isNegative {
|
||||
lhs.words[lhs.words.count - 1] |= (UInt.max << Int(remainder))
|
||||
}
|
||||
}
|
||||
|
||||
BigInt._dropExcessWords(words: &lhs.words)
|
||||
}
|
||||
|
||||
public static func >>= <RHS>(lhs: inout BigInt, rhs: RHS) where RHS: BinaryInteger {
|
||||
if rhs.signum() < 0 {
|
||||
lhs <<= rhs.magnitude
|
||||
return
|
||||
}
|
||||
|
||||
let wordLength = UInt.bitWidth
|
||||
let isNegative = lhs._isNegative
|
||||
|
||||
let (fullWords, remainder) = rhs.quotientAndRemainder(dividingBy: RHS(wordLength))
|
||||
if fullWords < lhs.words.count {
|
||||
lhs.words.removeFirst(Int(fullWords))
|
||||
} else {
|
||||
lhs = isNegative ? -1 : 0
|
||||
return
|
||||
}
|
||||
|
||||
if remainder > 0 {
|
||||
let mask = ~(UInt.max << remainder)
|
||||
var value: UInt = 0
|
||||
for i in stride(from: lhs.words.count - 1, through: 0, by: -1) {
|
||||
let temp = lhs.words[i] & mask
|
||||
lhs.words[i] >>= remainder
|
||||
lhs.words[i] |= (value << (UInt.bitWidth - Int(remainder)))
|
||||
value = temp
|
||||
}
|
||||
}
|
||||
|
||||
if isNegative {
|
||||
lhs.words[lhs.words.count - 1] |= (UInt.max << (UInt.bitWidth - Int(remainder)))
|
||||
}
|
||||
|
||||
BigInt._dropExcessWords(words: &lhs.words)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func quotientAndRemainder(dividingBy rhs: BigInt) -> (quotient: BigInt, remainder: BigInt) {
|
||||
return BigInt._div(lhs: self, rhs: rhs)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func signum() -> BigInt { _isNegative ? -1 : (self == 0) ? 0 : 1 }
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
extension BigInt {
|
||||
|
||||
/// See _The Art of Computer Programming_ volume 2 by Donald Knuth, Section 4.3.1: The Classical Algorithms
|
||||
private static func _findQhat(
|
||||
high: UInt,
|
||||
low: UInt.Magnitude,
|
||||
divisor: UInt,
|
||||
nextVdigit: UInt,
|
||||
nextUdigit: UInt
|
||||
) -> UInt {
|
||||
var qhat: Array<UInt>
|
||||
var rhat: Array<UInt>
|
||||
if high >= divisor {
|
||||
let v = divisor
|
||||
let u = [low, high]
|
||||
var r: UInt = 0
|
||||
qhat = Words(repeating: 0, count: 2)
|
||||
for j in (0...1).reversed() {
|
||||
let uj = u[j]
|
||||
(qhat[j], r) = v.dividingFullWidth((r, uj))
|
||||
}
|
||||
|
||||
BigInt._dropExcessWords(words: &qhat)
|
||||
rhat = [r]
|
||||
} else {
|
||||
let (qhatWord, rhatWord) = divisor.dividingFullWidth((high, low))
|
||||
qhat = [qhatWord]
|
||||
rhat = [rhatWord]
|
||||
}
|
||||
|
||||
repeat {
|
||||
var qhatTooLarge = false
|
||||
|
||||
if qhat.count > 1 {
|
||||
qhatTooLarge = true
|
||||
} else {
|
||||
// All of the following is computing and checking qhat*v_n-2 > rhat*b + u_j+n-2
|
||||
// from TAoCP Volume 2 Section 4.3.1, Algorithm D, step D3
|
||||
let (comp_lhs_hi, comp_lhs_lo) = qhat[0].multipliedFullWidth(by: nextVdigit)
|
||||
|
||||
if comp_lhs_hi > rhat[0] {
|
||||
qhatTooLarge = true
|
||||
} else if comp_lhs_hi == rhat[0] && comp_lhs_lo > nextUdigit {
|
||||
qhatTooLarge = true
|
||||
}
|
||||
}
|
||||
|
||||
// high >= divisor is standing in for the test qhat >= b from Algorithm D step D3
|
||||
if qhatTooLarge {
|
||||
// begin qhat -= 1
|
||||
if qhat.count == 1 {
|
||||
qhat[0] -= 1
|
||||
} else {
|
||||
let (qlow, underflow) = qhat[0].subtractingReportingOverflow(1)
|
||||
qhat[0] = qlow
|
||||
if qhat[1] > 0 && underflow {
|
||||
qhat[1] -= 1
|
||||
if qhat[1] == 0 {
|
||||
qhat.remove(at: 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
// end qhat -= 1
|
||||
|
||||
// begin rhat += divisor
|
||||
let (rhatResult, overflow) : (UInt, Bool)
|
||||
if rhat.count == 1 || rhat[1] == 0 {
|
||||
(rhatResult, overflow) = rhat[0].addingReportingOverflow(divisor)
|
||||
rhat[0] = rhatResult
|
||||
if overflow {
|
||||
rhat.append(1)
|
||||
}
|
||||
} // we don't need an else because rhat is already larger than BigInt._digitRadix
|
||||
// end rhat += divisor
|
||||
} else {
|
||||
break
|
||||
}
|
||||
} while rhat.count == 1 // equivalent to rhat < b
|
||||
|
||||
return qhat[0]
|
||||
}
|
||||
|
||||
/// See _The Art of Computer Programming_ volume 2 by Donald Knuth, Section 4.3.1: The Classical Algorithms
|
||||
@usableFromInline
|
||||
internal static func _div(lhs: BigInt, rhs: BigInt) -> (quotient: BigInt, remainder: BigInt) {
|
||||
precondition(rhs != _digits[0], "Division by zero error!")
|
||||
|
||||
if lhs.words.count == 1, rhs.words.count == 1 {
|
||||
let (quot, rem) = Int(bitPattern: lhs.words[0]).quotientAndRemainder(dividingBy: Int(bitPattern: rhs.words[0]))
|
||||
return (BigInt(_uncheckedWords: [UInt(bitPattern: quot)]), BigInt(_uncheckedWords: [UInt(bitPattern: rem)]))
|
||||
}
|
||||
|
||||
let lhsIsNeg = lhs._isNegative
|
||||
let rhsIsNeg = rhs._isNegative
|
||||
|
||||
var lhsWords = lhsIsNeg ? (-lhs).words : lhs.words
|
||||
var rhsWords = rhsIsNeg ? (-rhs).words : rhs.words
|
||||
|
||||
// See the answer to exercise 16 in Section 4.3.1 of TAOCP
|
||||
if rhsWords.count == 1 || (rhsWords.count == 2 && rhsWords[1] == 0) {
|
||||
let v = rhsWords[0]
|
||||
let u = lhsWords
|
||||
var r: UInt = 0
|
||||
var quot = Words(repeating: 0, count: u.count)
|
||||
for j in (0...(u.count - 1)).reversed() {
|
||||
let uj = u[j]
|
||||
(quot[j], r) = v.dividingFullWidth((r, uj))
|
||||
}
|
||||
|
||||
if quot[u.count - 1] > UInt(Int.max) {
|
||||
quot.append(0)
|
||||
}
|
||||
|
||||
BigInt._dropExcessWords(words: ")
|
||||
return (quotient: BigInt(_uncheckedWords: quot), remainder: BigInt(r))
|
||||
}
|
||||
|
||||
while rhsWords[rhsWords.endIndex - 1] == 0 {
|
||||
rhsWords.removeLast()
|
||||
}
|
||||
|
||||
if rhsWords.count > lhsWords.count { return (0, lhs) }
|
||||
|
||||
if lhsWords.count <= rhsWords.count {
|
||||
for _ in 0 ... (rhsWords.count - lhsWords.count) {
|
||||
lhsWords.append(0)
|
||||
}
|
||||
}
|
||||
|
||||
let m = lhsWords.count - rhsWords.count
|
||||
let n = rhsWords.count
|
||||
|
||||
let bitWidth = UInt(UInt.bitWidth)
|
||||
|
||||
let s = UInt(rhsWords[n - 1].leadingZeroBitCount)
|
||||
let rn = UnsafeMutablePointer<UInt>.allocate(capacity: n)
|
||||
rn.initialize(repeating: 0, count: n)
|
||||
defer { rn.deallocate() }
|
||||
for i in (1 ... (n - 1)).reversed() {
|
||||
rn[i] = (rhsWords[i] << s) | (rhsWords[i - 1] >> (bitWidth - s))
|
||||
}
|
||||
rn[0] = rhsWords[0] << s
|
||||
|
||||
let ln = UnsafeMutablePointer<UInt>.allocate(capacity: m + n + 1)
|
||||
ln.initialize(repeating: 0, count: m + n + 1)
|
||||
defer { ln.deallocate() }
|
||||
ln[m + n] = lhsWords[m + n - 1] >> (bitWidth - s)
|
||||
for i in (1 ... (m + n - 1)).reversed() {
|
||||
ln[i] = (lhsWords[i] << s) | (lhsWords[i - 1] >> (bitWidth - s))
|
||||
}
|
||||
ln[0] = lhsWords[0] << s
|
||||
|
||||
let resultSize = m + 1
|
||||
var quot = Words(repeating: 0, count: resultSize)
|
||||
|
||||
for j in (0 ... m).reversed() {
|
||||
let qhat = _findQhat(
|
||||
high: ln[j + n],
|
||||
low: UInt.Magnitude(ln[j + n - 1]),
|
||||
divisor: rn[n - 1],
|
||||
nextVdigit: rn[n - 2],
|
||||
nextUdigit: ln[j + n - 2])
|
||||
|
||||
var carry: UInt = 0
|
||||
var isOverflow = false
|
||||
var borrow: UInt = 0
|
||||
var underflow = false
|
||||
for i in 0 ..< n {
|
||||
if borrow > 0 {
|
||||
(ln[i + j], underflow) = ln[i + j].subtractingReportingOverflow(borrow)
|
||||
borrow = underflow ? 1 : 0
|
||||
}
|
||||
|
||||
var (pHigh, pLow) = qhat.multipliedFullWidth(by: rn[i])
|
||||
(pLow, isOverflow) = pLow.addingReportingOverflow(carry)
|
||||
if isOverflow {
|
||||
pHigh += 1
|
||||
}
|
||||
|
||||
(ln[i + j], underflow) = ln[i + j].subtractingReportingOverflow(pLow)
|
||||
if underflow {
|
||||
borrow += 1
|
||||
}
|
||||
|
||||
carry = pHigh
|
||||
}
|
||||
|
||||
(ln[j + n], underflow) = ln[j + n].subtractingReportingOverflow(carry + borrow)
|
||||
|
||||
if underflow {
|
||||
let newQhat = qhat - 1
|
||||
|
||||
carry = 0
|
||||
var total: UInt = 0
|
||||
for i in 0 ..< n {
|
||||
(total, isOverflow) = ln[i + j].addingReportingOverflow(carry)
|
||||
carry = isOverflow ? 1 : 0
|
||||
(ln[i + j], isOverflow) = total.addingReportingOverflow(rn[i])
|
||||
if carry == 0 { carry = isOverflow ? 1 : 0 }
|
||||
}
|
||||
(ln[j + n], _) = ln[j + n].addingReportingOverflow(carry)
|
||||
|
||||
quot[j] = newQhat
|
||||
} else {
|
||||
quot[j] = qhat
|
||||
}
|
||||
}
|
||||
|
||||
var rem = Words(repeating: 0, count: n)
|
||||
|
||||
for i in 0 ..< (n - 1) {
|
||||
rem[i] = (ln[i] >> s) | ln[i + 1] << (bitWidth - s)
|
||||
}
|
||||
rem[n - 1] = ln[n - 1] >> s
|
||||
|
||||
if rem[n - 1] > UInt(Int.max) {
|
||||
rem.append(0)
|
||||
}
|
||||
|
||||
BigInt._dropExcessWords(words: ")
|
||||
BigInt._dropExcessWords(words: &rem)
|
||||
|
||||
return (BigInt(_uncheckedWords: quot), BigInt(_uncheckedWords: rem))
|
||||
}
|
||||
|
||||
private static func _signExtend(lhsWords: inout Words, rhsWords: inout Words) {
|
||||
let lhsIsNeg = (lhsWords.last ?? 0) >> (UInt.bitWidth - Int(1)) == 1
|
||||
let rhsIsNeg = (rhsWords.last ?? 0) >> (UInt.bitWidth - Int(1)) == 1
|
||||
|
||||
if lhsWords.count > rhsWords.count {
|
||||
for _ in 0 ..< (lhsWords.count - rhsWords.count) {
|
||||
rhsIsNeg ? rhsWords.append(UInt.max) : rhsWords.append(0)
|
||||
}
|
||||
} else if rhsWords.count > lhsWords.count {
|
||||
for _ in 0 ..< (rhsWords.count - lhsWords.count) {
|
||||
lhsIsNeg ? lhsWords.append(UInt.max) : lhsWords.append(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal static func _dropExcessWords(words: inout Words) {
|
||||
while words.count > 1, words[words.endIndex - 1] == 0 {
|
||||
if words[words.endIndex - 2] <= Int.max {
|
||||
words.removeLast()
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
while words.count > 1, words[words.endIndex - 1] == UInt.max {
|
||||
if words[words.endIndex - 2] > Int.max {
|
||||
words.removeLast()
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,751 @@
|
||||
//===--- BigUInt.swift ----------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019 - 2020 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
public struct BigUInt: UnsignedInteger {
|
||||
|
||||
public typealias Words = [UInt]
|
||||
|
||||
public private(set) var words: Words
|
||||
|
||||
@usableFromInline
|
||||
internal init(_uncheckedWords: Words) {
|
||||
self.words = _uncheckedWords
|
||||
}
|
||||
|
||||
public init<T>(bitPattern source: T) where T: BinaryInteger {
|
||||
words = Words(source.words)
|
||||
BigUInt._dropExcessWords(words: &words)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal var _isNegative: Bool {
|
||||
words[words.endIndex - 1] > Int.max
|
||||
}
|
||||
|
||||
private static let _digits: [BigUInt] = (0 ... 36).map {
|
||||
BigUInt(_uncheckedWords: [UInt(bitPattern: $0)])
|
||||
}
|
||||
|
||||
private static let _digitRadix = BigInt(_uncheckedWords: [0, 1])
|
||||
}
|
||||
|
||||
// MARK: - Basic Behaviors
|
||||
|
||||
extension BigUInt: Equatable {
|
||||
|
||||
@inlinable
|
||||
public static func == (lhs: BigUInt, rhs: BigUInt) -> Bool {
|
||||
lhs.words == rhs.words
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func != (lhs: BigUInt, rhs: BigUInt) -> Bool {
|
||||
!(lhs == rhs)
|
||||
}
|
||||
}
|
||||
|
||||
extension BigUInt: Hashable {
|
||||
|
||||
@inlinable
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(words)
|
||||
}
|
||||
}
|
||||
|
||||
extension BigUInt: Comparable {
|
||||
|
||||
@inlinable
|
||||
public static func < (lhs: BigUInt, rhs: BigUInt) -> Bool {
|
||||
let lhsNegative = lhs._isNegative
|
||||
let rhsNegative = rhs._isNegative
|
||||
|
||||
if lhsNegative && !rhsNegative { return true }
|
||||
if rhsNegative && !lhsNegative { return false }
|
||||
|
||||
if (lhsNegative && rhsNegative) || (!lhsNegative && !rhsNegative) {
|
||||
if lhs.words.count > rhs.words.count {
|
||||
return lhsNegative ? true : false
|
||||
}
|
||||
if lhs.words.count < rhs.words.count {
|
||||
return lhsNegative ? false : true
|
||||
}
|
||||
|
||||
for i in stride(from: lhs.words.count - 1, through: 0, by: -1) {
|
||||
if lhs.words[i] > rhs.words[i] {
|
||||
return false
|
||||
} else if lhs.words[i] < rhs.words[i] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
extension BigUInt: LosslessStringConvertible {
|
||||
|
||||
public init?(_ description: String) {
|
||||
self.init(description, radix: 10)
|
||||
}
|
||||
|
||||
public init?<T>(_ description: T, radix: Int = 10) where T: StringProtocol {
|
||||
precondition(2 ... 36 ~= radix, "Radix not in range 2 ... 36")
|
||||
|
||||
self = 0
|
||||
|
||||
let hasPrefix = description.hasPrefix("+")
|
||||
let utf8 = description.utf8.dropFirst(hasPrefix ? 1 : 0)
|
||||
guard !utf8.isEmpty else { return nil }
|
||||
|
||||
for var byte in utf8 {
|
||||
switch byte {
|
||||
case UInt8(ascii: "0") ... UInt8(ascii: "9"):
|
||||
byte -= UInt8(ascii: "0")
|
||||
case UInt8(ascii: "A") ... UInt8(ascii: "Z"):
|
||||
byte -= UInt8(ascii: "A")
|
||||
byte += 10
|
||||
case UInt8(ascii: "a") ... UInt8(ascii: "z"):
|
||||
byte -= UInt8(ascii: "a")
|
||||
byte += 10
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
guard byte < radix else { return nil }
|
||||
self *= BigUInt._digits[radix]
|
||||
self += BigUInt._digits[Int(byte)]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension BigUInt: Decodable {
|
||||
|
||||
public init(from decoder: Decoder) throws {
|
||||
let singleValueContainer = try decoder.singleValueContainer()
|
||||
let description = try singleValueContainer.decode(String.self)
|
||||
guard let result = BigUInt(description) else {
|
||||
throw DecodingError.dataCorruptedError(
|
||||
in: singleValueContainer,
|
||||
debugDescription: "BigUInt(\(description.debugDescription)) failed")
|
||||
}
|
||||
self = result
|
||||
}
|
||||
}
|
||||
|
||||
extension BigUInt: Encodable {
|
||||
|
||||
public func encode(to encoder: Encoder) throws {
|
||||
var singleValueContainer = encoder.singleValueContainer()
|
||||
try singleValueContainer.encode(description)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Numeric Protocols
|
||||
|
||||
extension BigUInt: ExpressibleByIntegerLiteral {
|
||||
|
||||
public init(integerLiteral value: Int) {
|
||||
if value < BigUInt._digits.count {
|
||||
self = BigUInt._digits[value]
|
||||
} else {
|
||||
words = [UInt(bitPattern: value)]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension BigUInt: AdditiveArithmetic {
|
||||
|
||||
@inlinable
|
||||
public static func + (lhs: BigUInt, rhs: BigUInt) -> BigUInt {
|
||||
var result = lhs
|
||||
result += rhs
|
||||
return result
|
||||
}
|
||||
|
||||
public static func += (lhs: inout BigUInt, rhs: BigUInt) {
|
||||
if lhs.words.count == 1, rhs.words.count == 1 {
|
||||
let lhsWord = lhs.words[0]
|
||||
let rhsWord = rhs.words[0]
|
||||
|
||||
let (result, isOverflow) = lhsWord.addingReportingOverflow(rhsWord)
|
||||
|
||||
if !isOverflow && result < Int.max {
|
||||
lhs.words[0] = result
|
||||
return
|
||||
}
|
||||
let knownNegativeResult = lhsWord > Int.max && rhsWord > Int.max
|
||||
|
||||
if lhsWord > Int.max || rhsWord > Int.max, !knownNegativeResult {
|
||||
// positive + negative is always smaller, so overflow is a red herring
|
||||
lhs.words[0] = result
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var isOverflow = false
|
||||
|
||||
var rhsWords = rhs.words
|
||||
|
||||
lhs.words.append(0)
|
||||
rhsWords.append(0)
|
||||
BigUInt._zeroExtend(lhsWords: &lhs.words, rhsWords: &rhsWords)
|
||||
|
||||
var temp: UInt = 0
|
||||
for index in 0 ..< lhs.words.count {
|
||||
var carryOverflow = false
|
||||
|
||||
if isOverflow {
|
||||
(temp, carryOverflow) = rhsWords[index].addingReportingOverflow(1)
|
||||
} else {
|
||||
temp = rhsWords[index]
|
||||
}
|
||||
|
||||
(lhs.words[index], isOverflow) = lhs.words[index].addingReportingOverflow(temp)
|
||||
|
||||
isOverflow = carryOverflow || isOverflow
|
||||
}
|
||||
|
||||
BigUInt._dropExcessWords(words: &lhs.words)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func - (lhs: BigUInt, rhs: BigUInt) -> BigUInt {
|
||||
var result = lhs
|
||||
result -= rhs
|
||||
return result
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func -= (lhs: inout BigUInt, rhs: BigUInt) {
|
||||
lhs = .init(_uncheckedWords: (BigInt(_uncheckedWords: lhs.words) + -BigInt(_uncheckedWords: rhs.words)).words)
|
||||
}
|
||||
}
|
||||
|
||||
extension BigUInt: Numeric {
|
||||
|
||||
public init?<T>(exactly source: T) where T: BinaryInteger {
|
||||
self.init(source)
|
||||
}
|
||||
|
||||
public var magnitude: BigUInt { self }
|
||||
|
||||
public static func * (lhs: BigUInt, rhs: BigUInt) -> BigUInt {
|
||||
let lhsWords = lhs.words
|
||||
let rhsWords = rhs.words
|
||||
|
||||
let count = lhsWords.count + rhsWords.count + 1
|
||||
var newWords = Words(repeating: 0, count: count)
|
||||
|
||||
for i in 0 ..< rhsWords.count {
|
||||
var carry: UInt = 0
|
||||
var digit: UInt = 0
|
||||
|
||||
var lastJ: Int = 0
|
||||
for j in i ..< (lhsWords.count + i) {
|
||||
var (high, low) = rhsWords[i].multipliedFullWidth(by: lhsWords[j - i])
|
||||
var isOverflow: Bool
|
||||
(digit, isOverflow) = low.addingReportingOverflow(newWords[j])
|
||||
if isOverflow {
|
||||
high += 1
|
||||
}
|
||||
|
||||
(digit, isOverflow) = digit.addingReportingOverflow(carry)
|
||||
if isOverflow {
|
||||
high += 1
|
||||
}
|
||||
|
||||
carry = high
|
||||
newWords[j] = digit
|
||||
lastJ = j
|
||||
}
|
||||
|
||||
if carry != 0 {
|
||||
let isOverflow: Bool
|
||||
(digit, isOverflow) = newWords[lastJ + 1].addingReportingOverflow(carry)
|
||||
if isOverflow {
|
||||
carry = 1
|
||||
}
|
||||
newWords[lastJ + 1] = digit
|
||||
}
|
||||
}
|
||||
|
||||
for i in stride(from: count - 1, through: 1, by: -1) {
|
||||
if newWords[i] == 0, newWords[i - 1] <= Int.max {
|
||||
newWords.removeLast()
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return BigUInt(_uncheckedWords: newWords)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func *= (lhs: inout BigUInt, rhs: BigUInt) {
|
||||
lhs = lhs * rhs
|
||||
}
|
||||
}
|
||||
|
||||
extension BigUInt: BinaryInteger {
|
||||
|
||||
public init?<T>(exactly source: T) where T: BinaryFloatingPoint {
|
||||
guard source.isFinite, source == source.rounded(.towardZero) else {
|
||||
return nil
|
||||
}
|
||||
self.init(source)
|
||||
}
|
||||
|
||||
public init<T>(_ source: T) where T: BinaryFloatingPoint {
|
||||
precondition(
|
||||
source.isFinite && source >= 0.0,
|
||||
"""
|
||||
\(type(of: source)) value cannot be converted to BigUInt because it is \
|
||||
either infinite, NaN, or negative
|
||||
""")
|
||||
|
||||
var float = source
|
||||
|
||||
if let _ = UInt(exactly: T.greatestFiniteMagnitude) {
|
||||
words = [UInt(float)]
|
||||
} else {
|
||||
var words = Words()
|
||||
let radix = T(sign: .plus, exponent: T.Exponent(UInt.bitWidth), significand: 1)
|
||||
repeat {
|
||||
let digit = UInt(float.truncatingRemainder(dividingBy: radix))
|
||||
words.append(digit)
|
||||
float = (float / radix).rounded(.towardZero)
|
||||
} while float != 0
|
||||
|
||||
if let last = words.last, last >= Int.max {
|
||||
words.append(0)
|
||||
}
|
||||
self.words = words
|
||||
}
|
||||
}
|
||||
|
||||
public init<T>(_ source: T) where T: BinaryInteger {
|
||||
if source >= 0, source < BigUInt._digits.count {
|
||||
self = BigUInt._digits[Int(source)]
|
||||
} else {
|
||||
words = Words(source.words)
|
||||
if source > 0 && source.words[source.words.endIndex - 1] > Int.max {
|
||||
words.append(0)
|
||||
}
|
||||
// needed to handle sign-extended multi-word numbers that
|
||||
// actually fit in a single word
|
||||
BigUInt._dropExcessWords(words: &words)
|
||||
}
|
||||
}
|
||||
|
||||
public init<T>(clamping source: T) where T: BinaryInteger {
|
||||
self.init(source)
|
||||
}
|
||||
|
||||
public init<T>(truncatingIfNeeded source: T) where T: BinaryInteger {
|
||||
words = Words(source.words)
|
||||
}
|
||||
|
||||
public var bitWidth: Int { words.count * UInt.bitWidth }
|
||||
|
||||
public var trailingZeroBitCount: Int {
|
||||
var totalZeros = 0
|
||||
for word in words {
|
||||
if word == 0 {
|
||||
totalZeros += UInt.bitWidth
|
||||
} else {
|
||||
totalZeros += word.trailingZeroBitCount
|
||||
break
|
||||
}
|
||||
}
|
||||
return totalZeros
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func / (lhs: BigUInt, rhs: BigUInt) -> BigUInt {
|
||||
let (result, _) = _div(lhs: lhs, rhs: rhs)
|
||||
return result
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func /= (lhs: inout BigUInt, rhs: BigUInt) {
|
||||
lhs = lhs / rhs
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func % (lhs: BigUInt, rhs: BigUInt) -> BigUInt {
|
||||
let (_, result) = _div(lhs: lhs, rhs: rhs)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static func %= (lhs: inout BigUInt, rhs: BigUInt) {
|
||||
lhs = lhs % rhs
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public static prefix func ~ (x: BigUInt) -> BigUInt {
|
||||
let newWords = x.words.map { ~$0 }
|
||||
return BigUInt(_uncheckedWords: Words(newWords))
|
||||
}
|
||||
|
||||
public static func &= (lhs: inout BigUInt, rhs: BigUInt) {
|
||||
var rhsWords = rhs.words
|
||||
BigUInt._zeroExtend(lhsWords: &lhs.words, rhsWords: &rhsWords)
|
||||
|
||||
for i in 0 ..< rhsWords.count {
|
||||
lhs.words[i] &= rhsWords[i]
|
||||
}
|
||||
|
||||
BigUInt._dropExcessWords(words: &lhs.words)
|
||||
}
|
||||
|
||||
public static func |= (lhs: inout BigUInt, rhs: BigUInt) {
|
||||
var rhsWords = rhs.words
|
||||
BigUInt._zeroExtend(lhsWords: &lhs.words, rhsWords: &rhsWords)
|
||||
|
||||
for i in 0 ..< rhsWords.count {
|
||||
lhs.words[i] |= rhsWords[i]
|
||||
}
|
||||
|
||||
BigUInt._dropExcessWords(words: &lhs.words)
|
||||
}
|
||||
|
||||
public static func ^= (lhs: inout BigUInt, rhs: BigUInt) {
|
||||
var rhsWords = rhs.words
|
||||
BigUInt._zeroExtend(lhsWords: &lhs.words, rhsWords: &rhsWords)
|
||||
|
||||
for i in 0 ..< rhsWords.count {
|
||||
lhs.words[i] &= rhsWords[i]
|
||||
}
|
||||
|
||||
BigUInt._dropExcessWords(words: &lhs.words)
|
||||
}
|
||||
|
||||
public static func <<= <RHS>(lhs: inout BigUInt, rhs: RHS) where RHS: BinaryInteger {
|
||||
if rhs.signum() < 0 {
|
||||
lhs >>= rhs.magnitude
|
||||
return
|
||||
}
|
||||
|
||||
let wordLength = UInt.bitWidth
|
||||
|
||||
let (fullWords, remainder) = rhs.quotientAndRemainder(dividingBy: RHS(wordLength))
|
||||
lhs.words = Words(repeating: 0, count: Int(fullWords)) + lhs.words + [0]
|
||||
|
||||
if remainder > 0 {
|
||||
var value: UInt = 0
|
||||
for i in 0 ..< lhs.words.count {
|
||||
let temp = lhs.words[i] >> (wordLength - Int(remainder))
|
||||
lhs.words[i] <<= Int(remainder)
|
||||
if i > 0 {
|
||||
lhs.words[i] &= UInt.max << Int(remainder)
|
||||
lhs.words[i] |= value
|
||||
}
|
||||
|
||||
value = temp
|
||||
}
|
||||
}
|
||||
|
||||
BigUInt._dropExcessWords(words: &lhs.words)
|
||||
}
|
||||
|
||||
public static func >>= <RHS>(lhs: inout BigUInt, rhs: RHS) where RHS: BinaryInteger {
|
||||
if rhs.signum() < 0 {
|
||||
lhs <<= rhs.magnitude
|
||||
return
|
||||
}
|
||||
|
||||
let wordLength = UInt.bitWidth
|
||||
|
||||
let (fullWords, remainder) = rhs.quotientAndRemainder(dividingBy: RHS(wordLength))
|
||||
if fullWords < lhs.words.count {
|
||||
lhs.words.removeFirst(Int(fullWords))
|
||||
} else {
|
||||
lhs = 0
|
||||
return
|
||||
}
|
||||
|
||||
if remainder > 0 {
|
||||
let mask = ~(UInt.max << remainder)
|
||||
var value: UInt = 0
|
||||
for i in stride(from: lhs.words.count - 1, through: 0, by: -1) {
|
||||
let temp = lhs.words[i] & mask
|
||||
lhs.words[i] >>= remainder
|
||||
lhs.words[i] |= (value << (UInt.bitWidth - Int(remainder)))
|
||||
value = temp
|
||||
}
|
||||
}
|
||||
|
||||
BigUInt._dropExcessWords(words: &lhs.words)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func quotientAndRemainder(dividingBy rhs: BigUInt) -> (quotient: BigUInt, remainder: BigUInt) {
|
||||
return BigUInt._div(lhs: self, rhs: rhs)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
extension BigUInt {
|
||||
|
||||
/// See _The Art of Computer Programming_ volume 2 by Donald Knuth, Section 4.3.1: The Classical Algorithms
|
||||
private static func _findQhat(
|
||||
high: UInt,
|
||||
low: UInt.Magnitude,
|
||||
divisor: UInt,
|
||||
nextVdigit: UInt,
|
||||
nextUdigit: UInt
|
||||
) -> UInt {
|
||||
var qhat: Array<UInt>
|
||||
var rhat: Array<UInt>
|
||||
if high >= divisor {
|
||||
let v = divisor
|
||||
let u = [low, high]
|
||||
var r: UInt = 0
|
||||
qhat = Words(repeating: 0, count: 2)
|
||||
for j in (0...1).reversed() {
|
||||
let uj = u[j]
|
||||
(qhat[j], r) = v.dividingFullWidth((r, uj))
|
||||
}
|
||||
|
||||
BigUInt._dropExcessWords(words: &qhat)
|
||||
rhat = [r]
|
||||
} else {
|
||||
let (qhatWord, rhatWord) = divisor.dividingFullWidth((high, low))
|
||||
qhat = [qhatWord]
|
||||
rhat = [rhatWord]
|
||||
}
|
||||
|
||||
repeat {
|
||||
var qhatTooLarge = false
|
||||
|
||||
if qhat.count > 1 {
|
||||
qhatTooLarge = true
|
||||
} else {
|
||||
// All of the following is computing and checking qhat*v_n-2 > rhat*b + u_j+n-2
|
||||
// from TAoCP Volume 2 Section 4.3.1, Algorithm D, step D3
|
||||
let (comp_lhs_hi, comp_lhs_lo) = qhat[0].multipliedFullWidth(by: nextVdigit)
|
||||
|
||||
if comp_lhs_hi > rhat[0] {
|
||||
qhatTooLarge = true
|
||||
} else if comp_lhs_hi == rhat[0] && comp_lhs_lo > nextUdigit {
|
||||
qhatTooLarge = true
|
||||
}
|
||||
}
|
||||
|
||||
// high >= divisor is standing in for the test qhat >= b from Algorithm D step D3
|
||||
if qhatTooLarge {
|
||||
// begin qhat -= 1
|
||||
if qhat.count == 1 {
|
||||
qhat[0] -= 1
|
||||
} else {
|
||||
let (qlow, underflow) = qhat[0].subtractingReportingOverflow(1)
|
||||
qhat[0] = qlow
|
||||
if qhat[1] > 0 && underflow {
|
||||
qhat[1] -= 1
|
||||
if qhat[1] == 0 {
|
||||
qhat.remove(at: 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
// end qhat -= 1
|
||||
|
||||
// begin rhat += divisor
|
||||
let (rhatResult, overflow) : (UInt, Bool)
|
||||
if rhat.count == 1 || rhat[1] == 0 {
|
||||
(rhatResult, overflow) = rhat[0].addingReportingOverflow(divisor)
|
||||
rhat[0] = rhatResult
|
||||
if overflow {
|
||||
rhat.append(1)
|
||||
}
|
||||
} // we don't need an else because rhat is already larger than BigInt._digitRadix
|
||||
// end rhat += divisor
|
||||
} else {
|
||||
break
|
||||
}
|
||||
} while rhat.count == 1 // equivalent to rhat < b
|
||||
|
||||
return qhat[0]
|
||||
}
|
||||
|
||||
/// See _The Art of Computer Programming_ volume 2 by Donald Knuth, Section 4.3.1: The Classical Algorithms
|
||||
@usableFromInline
|
||||
internal static func _div(lhs: BigUInt, rhs: BigUInt) -> (quotient: BigUInt, remainder: BigUInt) {
|
||||
precondition(rhs != _digits[0], "Division by zero error!")
|
||||
|
||||
if lhs.words.count == 1, rhs.words.count == 1 {
|
||||
let (quot, rem) = Int(bitPattern: lhs.words[0]).quotientAndRemainder(dividingBy: Int(bitPattern: rhs.words[0]))
|
||||
return (BigUInt(_uncheckedWords: [UInt(bitPattern: quot)]), BigUInt(_uncheckedWords: [UInt(bitPattern: rem)]))
|
||||
}
|
||||
|
||||
var lhsWords = lhs.words
|
||||
var rhsWords = rhs.words
|
||||
|
||||
// See the answer to exercise 16 in Section 4.3.1 of TAOCP
|
||||
if rhsWords.count == 1 || (rhsWords.count == 2 && rhsWords[1] == 0) {
|
||||
let v = rhsWords[0]
|
||||
let u = lhsWords
|
||||
var r: UInt = 0
|
||||
var quot = Words(repeating: 0, count: u.count)
|
||||
for j in (0...(u.count - 1)).reversed() {
|
||||
let uj = u[j]
|
||||
(quot[j], r) = v.dividingFullWidth((r, uj))
|
||||
}
|
||||
|
||||
if quot[u.count - 1] > UInt(Int.max) {
|
||||
quot.append(0)
|
||||
}
|
||||
|
||||
BigUInt._dropExcessWords(words: ")
|
||||
return (quotient: BigUInt(_uncheckedWords: quot), remainder: BigUInt(r))
|
||||
}
|
||||
|
||||
while rhsWords[rhsWords.endIndex - 1] == 0 {
|
||||
rhsWords.removeLast()
|
||||
}
|
||||
|
||||
if rhsWords.count > lhsWords.count { return (0, lhs) }
|
||||
|
||||
if lhsWords.count <= rhsWords.count {
|
||||
for _ in 0 ... (rhsWords.count - lhsWords.count) {
|
||||
lhsWords.append(0)
|
||||
}
|
||||
}
|
||||
|
||||
let m = lhsWords.count - rhsWords.count
|
||||
let n = rhsWords.count
|
||||
|
||||
let bitWidth = UInt(UInt.bitWidth)
|
||||
|
||||
let s = UInt(rhsWords[n - 1].leadingZeroBitCount)
|
||||
let rn = UnsafeMutablePointer<UInt>.allocate(capacity: n)
|
||||
rn.initialize(repeating: 0, count: n)
|
||||
defer { rn.deallocate() }
|
||||
for i in (1 ... (n - 1)).reversed() {
|
||||
rn[i] = (rhsWords[i] << s) | (rhsWords[i - 1] >> (bitWidth - s))
|
||||
}
|
||||
rn[0] = rhsWords[0] << s
|
||||
|
||||
let ln = UnsafeMutablePointer<UInt>.allocate(capacity: m + n + 1)
|
||||
ln.initialize(repeating: 0, count: m + n + 1)
|
||||
defer { ln.deallocate() }
|
||||
ln[m + n] = lhsWords[m + n - 1] >> (bitWidth - s)
|
||||
for i in (1 ... (m + n - 1)).reversed() {
|
||||
ln[i] = (lhsWords[i] << s) | (lhsWords[i - 1] >> (bitWidth - s))
|
||||
}
|
||||
ln[0] = lhsWords[0] << s
|
||||
|
||||
let resultSize = m + 1
|
||||
var quot = Words(repeating: 0, count: resultSize)
|
||||
|
||||
for j in (0 ... m).reversed() {
|
||||
let qhat = _findQhat(
|
||||
high: ln[j + n],
|
||||
low: UInt.Magnitude(ln[j + n - 1]),
|
||||
divisor: rn[n - 1],
|
||||
nextVdigit: rn[n - 2],
|
||||
nextUdigit: ln[j + n - 2])
|
||||
|
||||
var carry: UInt = 0
|
||||
var isOverflow = false
|
||||
var borrow: UInt = 0
|
||||
var underflow = false
|
||||
for i in 0 ..< n {
|
||||
if borrow > 0 {
|
||||
(ln[i + j], underflow) = ln[i + j].subtractingReportingOverflow(borrow)
|
||||
borrow = underflow ? 1 : 0
|
||||
}
|
||||
|
||||
var (pHigh, pLow) = qhat.multipliedFullWidth(by: rn[i])
|
||||
(pLow, isOverflow) = pLow.addingReportingOverflow(carry)
|
||||
if isOverflow {
|
||||
pHigh += 1
|
||||
}
|
||||
|
||||
(ln[i + j], underflow) = ln[i + j].subtractingReportingOverflow(pLow)
|
||||
if underflow {
|
||||
borrow += 1
|
||||
}
|
||||
|
||||
carry = pHigh
|
||||
}
|
||||
|
||||
(ln[j + n], underflow) = ln[j + n].subtractingReportingOverflow(carry + borrow)
|
||||
|
||||
if underflow {
|
||||
let newQhat = qhat - 1
|
||||
|
||||
carry = 0
|
||||
var total: UInt = 0
|
||||
for i in 0 ..< n {
|
||||
(total, isOverflow) = ln[i + j].addingReportingOverflow(carry)
|
||||
carry = isOverflow ? 1 : 0
|
||||
(ln[i + j], isOverflow) = total.addingReportingOverflow(rn[i])
|
||||
if carry == 0 { carry = isOverflow ? 1 : 0 }
|
||||
}
|
||||
(ln[j + n], _) = ln[j + n].addingReportingOverflow(carry)
|
||||
|
||||
quot[j] = newQhat
|
||||
} else {
|
||||
quot[j] = qhat
|
||||
}
|
||||
}
|
||||
|
||||
var rem = Words(repeating: 0, count: n)
|
||||
|
||||
for i in 0 ..< (n - 1) {
|
||||
rem[i] = (ln[i] >> s) | ln[i + 1] << (bitWidth - s)
|
||||
}
|
||||
rem[n - 1] = ln[n - 1] >> s
|
||||
|
||||
if rem[n - 1] > UInt(Int.max) {
|
||||
rem.append(0)
|
||||
}
|
||||
|
||||
BigUInt._dropExcessWords(words: ")
|
||||
BigUInt._dropExcessWords(words: &rem)
|
||||
|
||||
return (BigUInt(_uncheckedWords: quot), BigUInt(_uncheckedWords: rem))
|
||||
}
|
||||
|
||||
private static func _zeroExtend(lhsWords: inout Words, rhsWords: inout Words) {
|
||||
if lhsWords.count > rhsWords.count {
|
||||
for _ in 0 ..< (lhsWords.count - rhsWords.count) {
|
||||
rhsWords.append(0)
|
||||
}
|
||||
} else if rhsWords.count > lhsWords.count {
|
||||
for _ in 0 ..< (rhsWords.count - lhsWords.count) {
|
||||
lhsWords.append(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
internal static func _dropExcessWords(words: inout Words) {
|
||||
while words.count > 1, words[words.endIndex - 1] == 0 {
|
||||
if words[words.endIndex - 2] <= Int.max {
|
||||
words.removeLast()
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
while words.count > 1, words[words.endIndex - 1] == UInt.max {
|
||||
if words[words.endIndex - 2] > Int.max {
|
||||
words.removeLast()
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
#[[
|
||||
This source file is part of the Swift Numerics open source project
|
||||
|
||||
Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
|
||||
Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
#]]
|
||||
|
||||
add_library(BigIntModule
|
||||
BigInt.swift)
|
||||
set_target_properties(BigIntModule PROPERTIES
|
||||
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
|
||||
|
||||
_install_target(BigIntModule)
|
||||
set_property(GLOBAL APPEND PROPERTY SWIFT_NUMERICS_EXPORTS BigIntModule)
|
||||
@@ -0,0 +1,3 @@
|
||||
# Arbitrary-precision integers
|
||||
|
||||
This module provides a `BigInt` type.
|
||||
@@ -19,6 +19,7 @@ target_compile_options(Numerics PUBLIC
|
||||
# load symbol when validating the TBD
|
||||
-Xfrontend -validate-tbd-against-ir=none)
|
||||
target_link_libraries(Numerics PUBLIC
|
||||
BigIntModule
|
||||
ComplexModule
|
||||
IntegerUtilities
|
||||
RealModule)
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// A module that re-exports the complete Swift Numerics public API.
|
||||
@_exported import BigIntModule
|
||||
@_exported import ComplexModule
|
||||
@_exported import IntegerUtilities
|
||||
@_exported import RealModule
|
||||
@@ -0,0 +1,460 @@
|
||||
//===--- BigIntTests.swift ------------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019 - 2020 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import BigIntModule
|
||||
import XCTest
|
||||
|
||||
extension BigInt {
|
||||
|
||||
static func fac(_ n: BigInt) -> BigInt {
|
||||
precondition(n >= 0, "Factorial of a negative integer is undefined")
|
||||
return stride(from: n, to: 1, by: -1).reduce(into: 1, { $0 *= $1 })
|
||||
}
|
||||
|
||||
// inspired by https://eli.thegreenplace.net/2009/03/21/efficient-integer-exponentiation-algorithms
|
||||
static func pow(_ lhs: BigInt, _ rhs: BigInt) -> BigInt {
|
||||
let bits_of_n = {
|
||||
(n: BigInt) -> [Int] in
|
||||
var bits: [Int] = []
|
||||
var n = n
|
||||
while n != 0 {
|
||||
bits.append(Int(n % 2))
|
||||
n /= 2
|
||||
}
|
||||
|
||||
return bits
|
||||
}
|
||||
|
||||
var r: BigInt = 1
|
||||
for bit in bits_of_n(rhs).reversed() {
|
||||
r *= r
|
||||
if bit == 1 {
|
||||
r *= lhs
|
||||
}
|
||||
}
|
||||
|
||||
return r
|
||||
}
|
||||
}
|
||||
|
||||
final class BigIntTests: XCTestCase {
|
||||
|
||||
/// Python: `bitWidth = 1024; -(2 ** (bitWidth - 1))`
|
||||
static let descriptionInt1024Min: String =
|
||||
"""
|
||||
-89884656743115795386465259539451236680898848947115328636715040578866337902\
|
||||
750481566354238661203768010560056939935696678829394884407208311246423715319\
|
||||
737062188883946712432742638151109800623047059726541476042502884419075341171\
|
||||
231440736956555270413618581675255342293149119973622969239858152417678164812\
|
||||
112068608
|
||||
"""
|
||||
|
||||
/// Python: `bitWidth = 1024; (2 ** (bitWidth - 1)) - 1`
|
||||
static let descriptionInt1024Max: String =
|
||||
"""
|
||||
89884656743115795386465259539451236680898848947115328636715040578866337902\
|
||||
750481566354238661203768010560056939935696678829394884407208311246423715319\
|
||||
737062188883946712432742638151109800623047059726541476042502884419075341171\
|
||||
231440736956555270413618581675255342293149119973622969239858152417678164812\
|
||||
112068607
|
||||
"""
|
||||
|
||||
/// Python: `numpy.base_repr(math.factorial(512), base=36)`
|
||||
static let descriptionFactorial512_radix36: String =
|
||||
"""
|
||||
7FA5Y7EHR9XHMQ519MBHGYOF8XDYMUX8OZHO9WF1KCM0SSPXV2V45UA73BAFRYM2PFB8CZLTODV\
|
||||
OS3QWA7PYFJ7WAFBI4VF371E27N6XZ4LGWHMFDS4ZH1O3DGNFG4YABUE1G90ORGRTIOGSQVZLSQ\
|
||||
4TKHKHIQ262JVQ0J6LSKAPN5I65AJD33XODVHRNWJ1VSO0Q2FBOUNCPGQG2SFQKR17XHF1OLTV2\
|
||||
MVNJVTDAIYWVJ9ZH7KXT0EPS00IGIVC7MNCU25HFWE37KNMSJQUL5ALUCE5XZVPFQCQGEVEB93B\
|
||||
GA8LKG67PVZ7Q9QMQKIVNIMPT2973MVDTD1D1A0A4QT6NBZYR0TGSZXBV1PD0CHW4SKZJSLBS4Z\
|
||||
W5WCKDY8BCQCE17KKADVLCTVSQL1BZ2PL52DDPB8S5L0ZEG2ZAZF9V4TNJJNO1D9U9JU7B264QZ\
|
||||
5GLHC3Q0Y3BTECGTI8GRENQ2FV4HSEZKPM9OG302KLSY9MBCSOO0FN229AST84TT87LYWOOS71C\
|
||||
54RPJ9RTO9875Z9DE3HPH89EW5I3SV219O04UU09A4KME7DD7IH49ABO79NR4EXFX1VLL4YOHSA\
|
||||
7AHD1LS5YKZ66F4UPG0RCBGG000000000000000000000000000000000000000000000000000\
|
||||
000000000000000000000000000000000000000000000000000000000000000000000000000
|
||||
"""
|
||||
|
||||
// MARK: - Basic arithmetic
|
||||
|
||||
func testDivision() {
|
||||
let num1 = BigInt("18446744073709551616")!
|
||||
let den1 = BigInt(123)
|
||||
let expected1 = BigInt(UInt64(149973529054549200))
|
||||
XCTAssertEqual(num1 / den1, expected1)
|
||||
|
||||
let num2 = BigInt.pow(BigInt(10), 100)
|
||||
let den2: BigInt = 3
|
||||
let expected2: BigInt = BigInt(String(repeating: "3", count: 100))!
|
||||
let actual2 = num2 / den2
|
||||
XCTAssertEqual(actual2, expected2)
|
||||
|
||||
let num3 = BigInt.pow(BigInt(10), 97)
|
||||
let den3: BigInt = BigInt("33333333333333333333")!
|
||||
let expected3: BigInt = BigInt("300000000000000000003000000000000000000030000000000000000000300000000000000000")!
|
||||
let actual3 = num3 / den3
|
||||
XCTAssertEqual(actual3, expected3)
|
||||
|
||||
let foo = BigInt("12345678901234567890123456789012345678901234567890123456789012345678901234567890")!
|
||||
let bar = BigInt("351235231535161613134135135135")!
|
||||
let baz = foo / bar
|
||||
XCTAssertEqual(baz, BigInt("35149318157164029153358504918339691272847595997760")!)
|
||||
|
||||
XCTAssertNotNil(BigInt(exactly: 2.4e39))
|
||||
XCTAssertNotNil(BigInt(exactly: 1e38))
|
||||
XCTAssertEqual(BigInt(2.4e39) / BigInt(1e38), BigInt(24))
|
||||
|
||||
for _ in 0 ..< 100 {
|
||||
let expected = BigInt(Float64.random(in: 0x1p64 ... 0x1p255))
|
||||
let divisor = BigInt(Float64.random(in: 0x1p64 ... 0x1p128))
|
||||
let (quotient, remainder) = expected.quotientAndRemainder(dividingBy: divisor)
|
||||
let actual = divisor * quotient + remainder
|
||||
XCTAssertEqual(quotient, expected / divisor)
|
||||
XCTAssertEqual(remainder, expected % divisor)
|
||||
XCTAssertEqual(
|
||||
actual, expected,
|
||||
"""
|
||||
## FAILURE ##
|
||||
~~~~~~~~~~~~~
|
||||
actual: \(actual)
|
||||
!= expected: \(expected)
|
||||
~~~~~~~~~~~~~
|
||||
divisor: \(divisor)
|
||||
* quotient: \(quotient)
|
||||
+ remainder: \(remainder)
|
||||
~~~~~~~~~~~~~
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
func testFactorial() {
|
||||
var expectedNumber: BigInt?
|
||||
var actualNumber: BigInt!
|
||||
var actualString: String!
|
||||
|
||||
measure {
|
||||
expectedNumber = BigInt(Self.descriptionFactorial512_radix36, radix: 36)
|
||||
actualNumber = BigInt.fac(512)
|
||||
actualString = String(actualNumber, radix: 36, uppercase: true)
|
||||
}
|
||||
|
||||
XCTAssertEqual(actualNumber, expectedNumber)
|
||||
XCTAssertEqual(actualString, Self.descriptionFactorial512_radix36)
|
||||
|
||||
XCTAssertEqual(BigInt.fac(0), 1)
|
||||
XCTAssertEqual(BigInt.fac(1), 1)
|
||||
XCTAssertEqual(BigInt.fac(2), 2)
|
||||
XCTAssertEqual(BigInt.fac(3), 6)
|
||||
XCTAssertEqual(BigInt.fac(4), 24)
|
||||
XCTAssertEqual(BigInt.fac(5), 120)
|
||||
XCTAssertEqual(BigInt.fac(6), 720)
|
||||
XCTAssertEqual(BigInt.fac(7), 5040)
|
||||
XCTAssertEqual(BigInt.fac(8), 40320)
|
||||
XCTAssertEqual(BigInt.fac(9), 362880)
|
||||
}
|
||||
|
||||
func testMath() {
|
||||
let foo = BigInt.pow(10, 20)
|
||||
let bar = BigInt("1234567890123456789012345678901234567890")!
|
||||
|
||||
let baz = foo + bar
|
||||
|
||||
XCTAssertEqual(baz, BigInt("1234567890123456789112345678901234567890")!)
|
||||
|
||||
let fooz = foo >> BigInt(10)
|
||||
XCTAssertEqual(fooz, foo / 1024)
|
||||
|
||||
let barz = BigInt(1) << 64
|
||||
XCTAssertEqual(barz, BigInt(UInt64.max) + 1)
|
||||
}
|
||||
|
||||
func testNegation() {
|
||||
let foo = BigInt("1234567890123456789012345678901234567890")!
|
||||
let bar = BigInt(0) - foo
|
||||
|
||||
XCTAssertEqual(-foo, bar)
|
||||
|
||||
var baz = foo
|
||||
baz.negate()
|
||||
XCTAssertEqual(baz, bar)
|
||||
}
|
||||
|
||||
func testSignum() {
|
||||
XCTAssertEqual(BigInt(-0x1p1023).signum(), -1)
|
||||
XCTAssertEqual(BigInt(Int64.min).signum(), -1)
|
||||
XCTAssertEqual(BigInt(Int32.min).signum(), -1)
|
||||
XCTAssertEqual(BigInt(Int16.min).signum(), -1)
|
||||
XCTAssertEqual(BigInt(Int8.min).signum(), -1)
|
||||
XCTAssertEqual(BigInt(-1).signum(), -1)
|
||||
XCTAssertEqual(BigInt(0).signum(), 0)
|
||||
XCTAssertEqual(BigInt(+1).signum(), +1)
|
||||
XCTAssertEqual(BigInt(Int8.max).signum(), +1)
|
||||
XCTAssertEqual(BigInt(Int16.max).signum(), +1)
|
||||
XCTAssertEqual(BigInt(Int32.max).signum(), +1)
|
||||
XCTAssertEqual(BigInt(Int64.max).signum(), +1)
|
||||
XCTAssertEqual(BigInt(+0x1p1023).signum(), +1)
|
||||
}
|
||||
|
||||
func testTrailingZeroCount() {
|
||||
let foo = BigInt(1) << 300
|
||||
XCTAssertEqual(foo.trailingZeroBitCount, 300)
|
||||
|
||||
let bar = (BigInt(1) << 300) + 0b101000
|
||||
XCTAssertEqual(bar.trailingZeroBitCount, 3)
|
||||
}
|
||||
|
||||
// MARK: - Comparing and hashing
|
||||
|
||||
func testComparable() {
|
||||
let foo = BigInt("1234567890123456789012345678901234567890")!
|
||||
let bar = foo * foo
|
||||
|
||||
XCTAssertLessThan(foo, bar)
|
||||
XCTAssertFalse(foo < foo)
|
||||
XCTAssertFalse(bar < bar)
|
||||
XCTAssertFalse(foo > foo)
|
||||
XCTAssertFalse(bar > bar)
|
||||
XCTAssertGreaterThan(bar, foo)
|
||||
|
||||
let baz = bar * -1
|
||||
|
||||
XCTAssertLessThan(baz, foo)
|
||||
XCTAssertNotEqual(bar, baz)
|
||||
XCTAssertFalse(baz < baz)
|
||||
}
|
||||
|
||||
func testComparison() {
|
||||
let foo = BigInt(-10)
|
||||
let bar = BigInt(-20)
|
||||
|
||||
XCTAssert(foo > bar)
|
||||
XCTAssert(bar < foo)
|
||||
XCTAssert(foo == BigInt(-10))
|
||||
|
||||
let baz = BigInt.pow(foo, -bar)
|
||||
XCTAssertEqual(baz, BigInt("100000000000000000000")!)
|
||||
}
|
||||
|
||||
func testExample() {
|
||||
let bar = BigInt(exactly: -100)
|
||||
XCTAssertNotNil(bar)
|
||||
if let bar = bar {
|
||||
XCTAssertLessThan(bar, 0)
|
||||
XCTAssertGreaterThan(-bar, 0)
|
||||
XCTAssertEqual(-bar, BigInt(100))
|
||||
}
|
||||
XCTAssertEqual(-BigInt("-1234567890123456789012345678901234567890")!,
|
||||
+BigInt("+1234567890123456789012345678901234567890")!)
|
||||
}
|
||||
|
||||
func testHashable() {
|
||||
let foo = BigInt("1234567890123456789012345678901234567890")!
|
||||
let bar = BigInt("1234567890123456789112345678901234567890")!
|
||||
let baz: BigInt = 153
|
||||
|
||||
let dict = [ foo: "Hello", bar: "World", baz: "!" ]
|
||||
|
||||
let hash = foo.hashValue
|
||||
print(hash)
|
||||
|
||||
XCTAssertEqual(dict[foo]!, "Hello")
|
||||
XCTAssertEqual(dict[bar]!, "World")
|
||||
}
|
||||
|
||||
func testClampingConversion() {
|
||||
XCTAssertEqual(BigInt(clamping: UInt64.max), BigInt(UInt64(18446744073709551615)))
|
||||
}
|
||||
|
||||
func testUIntConversion() {
|
||||
let foo = BigInt(UInt.max)
|
||||
XCTAssertNotEqual(foo, BigInt(-1))
|
||||
|
||||
let bar = BigInt(bitPattern: UInt.max)
|
||||
XCTAssertEqual(bar, BigInt(-1))
|
||||
}
|
||||
|
||||
// MARK: - Converting to/from textual representations
|
||||
|
||||
func testCodable() throws {
|
||||
let lowerBound = BigInt("-1234567890123456789012345678901234567890")!
|
||||
let upperBound = BigInt("+1234567890123456789012345678901234567890")!
|
||||
let expectedRange: Range<BigInt> = lowerBound ..< upperBound
|
||||
|
||||
let encoder = JSONEncoder()
|
||||
let decoder = JSONDecoder()
|
||||
let data = try encoder.encode(expectedRange)
|
||||
let actualRange = try decoder.decode(Range<BigInt>.self, from: data)
|
||||
|
||||
XCTAssertEqual(actualRange, expectedRange)
|
||||
}
|
||||
|
||||
func testCustomStringConvertible() {
|
||||
XCTAssertEqual("\(BigInt(UInt64.min) - 2)", "-2")
|
||||
XCTAssertEqual("\(BigInt(UInt64.min) - 1)", "-1")
|
||||
XCTAssertEqual("\(BigInt(UInt64.min) + 0)", "0")
|
||||
XCTAssertEqual("\(BigInt(UInt64.min) + 1)", "1")
|
||||
XCTAssertEqual("\(BigInt(UInt64.min) + 2)", "2")
|
||||
|
||||
XCTAssertEqual("\(BigInt(UInt64.max) - 2)", "18446744073709551613")
|
||||
XCTAssertEqual("\(BigInt(UInt64.max) - 1)", "18446744073709551614")
|
||||
XCTAssertEqual("\(BigInt(UInt64.max) + 0)", "18446744073709551615")
|
||||
XCTAssertEqual("\(BigInt(UInt64.max) + 1)", "18446744073709551616")
|
||||
XCTAssertEqual("\(BigInt(UInt64.max) + 2)", "18446744073709551617")
|
||||
|
||||
XCTAssertEqual("\(BigInt(Int64.min) - 2)", "-9223372036854775810")
|
||||
XCTAssertEqual("\(BigInt(Int64.min) - 1)", "-9223372036854775809")
|
||||
XCTAssertEqual("\(BigInt(Int64.min) + 0)", "-9223372036854775808")
|
||||
XCTAssertEqual("\(BigInt(Int64.min) + 1)", "-9223372036854775807")
|
||||
XCTAssertEqual("\(BigInt(Int64.min) + 2)", "-9223372036854775806")
|
||||
|
||||
XCTAssertEqual("\(BigInt(Int64.max) - 2)", "9223372036854775805")
|
||||
XCTAssertEqual("\(BigInt(Int64.max) - 1)", "9223372036854775806")
|
||||
XCTAssertEqual("\(BigInt(Int64.max) + 0)", "9223372036854775807")
|
||||
XCTAssertEqual("\(BigInt(Int64.max) + 1)", "9223372036854775808")
|
||||
XCTAssertEqual("\(BigInt(Int64.max) + 2)", "9223372036854775809")
|
||||
|
||||
XCTAssertEqual("\(-(BigInt(1) << 1023))", Self.descriptionInt1024Min)
|
||||
XCTAssertEqual("\(+(BigInt(1) << 1023) - 1)", Self.descriptionInt1024Max)
|
||||
}
|
||||
|
||||
func testLosslessStringConvertible() {
|
||||
XCTAssertNil(BigInt(""))
|
||||
XCTAssertNil(BigInt("-"))
|
||||
XCTAssertNil(BigInt("+"))
|
||||
XCTAssertNil(BigInt("A"))
|
||||
XCTAssertNil(BigInt(" 0"))
|
||||
XCTAssertNil(BigInt("0 "))
|
||||
|
||||
XCTAssertEqual(BigInt(UInt64.min) - 2, BigInt("-2"))
|
||||
XCTAssertEqual(BigInt(UInt64.min) - 1, BigInt("-1"))
|
||||
XCTAssertEqual(BigInt(UInt64.min) + 0, BigInt("0"))
|
||||
XCTAssertEqual(BigInt(UInt64.min) + 1, BigInt("1"))
|
||||
XCTAssertEqual(BigInt(UInt64.min) + 2, BigInt("2"))
|
||||
|
||||
XCTAssertEqual(BigInt(UInt64.max) - 2, BigInt("18446744073709551613"))
|
||||
XCTAssertEqual(BigInt(UInt64.max) - 1, BigInt("18446744073709551614"))
|
||||
XCTAssertEqual(BigInt(UInt64.max) + 0, BigInt("18446744073709551615"))
|
||||
XCTAssertEqual(BigInt(UInt64.max) + 1, BigInt("18446744073709551616"))
|
||||
XCTAssertEqual(BigInt(UInt64.max) + 2, BigInt("18446744073709551617"))
|
||||
|
||||
XCTAssertEqual(BigInt(Int64.min) - 2, BigInt("-9223372036854775810"))
|
||||
XCTAssertEqual(BigInt(Int64.min) - 1, BigInt("-9223372036854775809"))
|
||||
XCTAssertEqual(BigInt(Int64.min) + 0, BigInt("-9223372036854775808"))
|
||||
XCTAssertEqual(BigInt(Int64.min) + 1, BigInt("-9223372036854775807"))
|
||||
XCTAssertEqual(BigInt(Int64.min) + 2, BigInt("-9223372036854775806"))
|
||||
|
||||
XCTAssertEqual(BigInt(Int64.max) - 2, BigInt("9223372036854775805"))
|
||||
XCTAssertEqual(BigInt(Int64.max) - 1, BigInt("9223372036854775806"))
|
||||
XCTAssertEqual(BigInt(Int64.max) + 0, BigInt("9223372036854775807"))
|
||||
XCTAssertEqual(BigInt(Int64.max) + 1, BigInt("9223372036854775808"))
|
||||
XCTAssertEqual(BigInt(Int64.max) + 2, BigInt("9223372036854775809"))
|
||||
|
||||
XCTAssertEqual(-(BigInt(1) << 1023), BigInt(Self.descriptionInt1024Min))
|
||||
XCTAssertEqual(+(BigInt(1) << 1023) - 1, BigInt(Self.descriptionInt1024Max))
|
||||
}
|
||||
|
||||
func testRadicesAndNumerals() {
|
||||
for radix in 2 ... 36 {
|
||||
for uppercase in [false, true] {
|
||||
for _ in 0 ..< 100 {
|
||||
let expectedNumber = BigInt(Int.random(in: .min ... .max))
|
||||
let expectedString = String(expectedNumber,
|
||||
radix: radix,
|
||||
uppercase: uppercase)
|
||||
let actualNumber = BigInt(expectedString, radix: radix)
|
||||
XCTAssertEqual(actualNumber, expectedNumber)
|
||||
if radix == 10 {
|
||||
let actualString = expectedNumber.description
|
||||
XCTAssertEqual(actualString, expectedString)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Converting from floating-point binary types
|
||||
|
||||
func testBinaryFloatingPoint<T>(_ type: T.Type) where T: BinaryFloatingPoint {
|
||||
var expected = BigInt(T.greatestFiniteMagnitude.significandBitPattern)
|
||||
expected |= BigInt(1) << T.significandBitCount
|
||||
expected <<= T.greatestFiniteMagnitude.exponent
|
||||
expected >>= T.significandBitCount
|
||||
|
||||
XCTAssertEqual(BigInt(exactly: -T.greatestFiniteMagnitude), -expected)
|
||||
XCTAssertEqual(BigInt(exactly: +T.greatestFiniteMagnitude), +expected)
|
||||
XCTAssertEqual(BigInt(-T.greatestFiniteMagnitude), -expected)
|
||||
XCTAssertEqual(BigInt(+T.greatestFiniteMagnitude), +expected)
|
||||
|
||||
XCTAssertNil(BigInt(exactly: -T.infinity))
|
||||
XCTAssertNil(BigInt(exactly: +T.infinity))
|
||||
|
||||
XCTAssertNil(BigInt(exactly: -T.leastNonzeroMagnitude))
|
||||
XCTAssertNil(BigInt(exactly: +T.leastNonzeroMagnitude))
|
||||
XCTAssertEqual(BigInt(-T.leastNonzeroMagnitude), 0)
|
||||
XCTAssertEqual(BigInt(+T.leastNonzeroMagnitude), 0)
|
||||
|
||||
XCTAssertNil(BigInt(exactly: -T.leastNormalMagnitude))
|
||||
XCTAssertNil(BigInt(exactly: +T.leastNormalMagnitude))
|
||||
XCTAssertEqual(BigInt(-T.leastNormalMagnitude), 0)
|
||||
XCTAssertEqual(BigInt(+T.leastNormalMagnitude), 0)
|
||||
|
||||
XCTAssertNil(BigInt(exactly: T.nan))
|
||||
XCTAssertNil(BigInt(exactly: T.signalingNaN))
|
||||
|
||||
XCTAssertNil(BigInt(exactly: -T.pi))
|
||||
XCTAssertNil(BigInt(exactly: +T.pi))
|
||||
XCTAssertEqual(BigInt(-T.pi), -3)
|
||||
XCTAssertEqual(BigInt(+T.pi), +3)
|
||||
|
||||
XCTAssertNil(BigInt(exactly: -T.ulpOfOne))
|
||||
XCTAssertNil(BigInt(exactly: +T.ulpOfOne))
|
||||
XCTAssertEqual(BigInt(-T.ulpOfOne), 0)
|
||||
XCTAssertEqual(BigInt(+T.ulpOfOne), 0)
|
||||
|
||||
XCTAssertEqual(BigInt(exactly: -T.zero), 0)
|
||||
XCTAssertEqual(BigInt(exactly: +T.zero), 0)
|
||||
XCTAssertEqual(BigInt(-T.zero), 0)
|
||||
XCTAssertEqual(BigInt(+T.zero), 0)
|
||||
}
|
||||
|
||||
func testBinaryFloatingPoint() {
|
||||
testBinaryFloatingPoint(Float32.self)
|
||||
testBinaryFloatingPoint(Float64.self)
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
testBinaryFloatingPoint(Float80.self)
|
||||
#endif
|
||||
|
||||
for _ in 0 ..< 100 {
|
||||
let small = Float32.random(in: -10 ... +10)
|
||||
XCTAssertEqual(BigInt(small), BigInt(Int64(small)))
|
||||
|
||||
let large = Float32.random(in: -0x1p23 ... +0x1p23)
|
||||
XCTAssertEqual(BigInt(large), BigInt(Int64(large)))
|
||||
}
|
||||
|
||||
for _ in 0 ..< 100 {
|
||||
let small = Float64.random(in: -10 ... +10)
|
||||
XCTAssertEqual(BigInt(small), BigInt(Int64(small)))
|
||||
|
||||
let large = Float64.random(in: -0x1p52 ... +0x1p52)
|
||||
XCTAssertEqual(BigInt(large), BigInt(Int64(large)))
|
||||
}
|
||||
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
for _ in 0 ..< 100 {
|
||||
let small = Float80.random(in: -10 ... +10)
|
||||
XCTAssertEqual(BigInt(small), BigInt(Int64(small)))
|
||||
|
||||
let large = Float80.random(in: -0x1p63 ..< +0x1p63)
|
||||
XCTAssertEqual(BigInt(large), BigInt(Int64(large)))
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
//===--- BigUIntTests.swift -----------------------------------*- swift -*-===//
|
||||
//
|
||||
// This source file is part of the Swift Numerics open source project
|
||||
//
|
||||
// Copyright (c) 2019 - 2020 Apple Inc. and the Swift Numerics project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception
|
||||
//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import BigIntModule
|
||||
import XCTest
|
||||
|
||||
extension BigUInt {
|
||||
|
||||
static func fac(_ n: BigUInt) -> BigUInt {
|
||||
return stride(from: n, to: 1, by: -1).reduce(into: 1, { $0 *= $1 })
|
||||
}
|
||||
|
||||
// inspired by https://eli.thegreenplace.net/2009/03/21/efficient-integer-exponentiation-algorithms
|
||||
static func pow(_ lhs: BigUInt, _ rhs: BigUInt) -> BigUInt {
|
||||
let bits_of_n = { (n: BigUInt) -> [Int] in
|
||||
var bits: [Int] = []
|
||||
var n = n
|
||||
while n != 0 {
|
||||
bits.append(Int(n % 2))
|
||||
n /= 2
|
||||
}
|
||||
|
||||
return bits
|
||||
}
|
||||
|
||||
var r: BigUInt = 1
|
||||
for bit in bits_of_n(rhs).reversed() {
|
||||
r *= r
|
||||
if bit == 1 {
|
||||
r *= lhs
|
||||
}
|
||||
}
|
||||
|
||||
return r
|
||||
}
|
||||
}
|
||||
|
||||
final class BigUIntTests: XCTestCase {
|
||||
|
||||
/// Python: `bitWidth = 1024; -(2 ** (bitWidth - 1))`
|
||||
static let descriptionInt1024Min: String =
|
||||
"""
|
||||
-89884656743115795386465259539451236680898848947115328636715040578866337902\
|
||||
750481566354238661203768010560056939935696678829394884407208311246423715319\
|
||||
737062188883946712432742638151109800623047059726541476042502884419075341171\
|
||||
231440736956555270413618581675255342293149119973622969239858152417678164812\
|
||||
112068608
|
||||
"""
|
||||
|
||||
/// Python: `bitWidth = 1024; (2 ** (bitWidth - 1)) - 1`
|
||||
static let descriptionInt1024Max: String =
|
||||
"""
|
||||
89884656743115795386465259539451236680898848947115328636715040578866337902\
|
||||
750481566354238661203768010560056939935696678829394884407208311246423715319\
|
||||
737062188883946712432742638151109800623047059726541476042502884419075341171\
|
||||
231440736956555270413618581675255342293149119973622969239858152417678164812\
|
||||
112068607
|
||||
"""
|
||||
|
||||
/// Python: `numpy.base_repr(math.factorial(512), base=36)`
|
||||
static let descriptionFactorial512_radix36: String =
|
||||
"""
|
||||
7FA5Y7EHR9XHMQ519MBHGYOF8XDYMUX8OZHO9WF1KCM0SSPXV2V45UA73BAFRYM2PFB8CZLTODV\
|
||||
OS3QWA7PYFJ7WAFBI4VF371E27N6XZ4LGWHMFDS4ZH1O3DGNFG4YABUE1G90ORGRTIOGSQVZLSQ\
|
||||
4TKHKHIQ262JVQ0J6LSKAPN5I65AJD33XODVHRNWJ1VSO0Q2FBOUNCPGQG2SFQKR17XHF1OLTV2\
|
||||
MVNJVTDAIYWVJ9ZH7KXT0EPS00IGIVC7MNCU25HFWE37KNMSJQUL5ALUCE5XZVPFQCQGEVEB93B\
|
||||
GA8LKG67PVZ7Q9QMQKIVNIMPT2973MVDTD1D1A0A4QT6NBZYR0TGSZXBV1PD0CHW4SKZJSLBS4Z\
|
||||
W5WCKDY8BCQCE17KKADVLCTVSQL1BZ2PL52DDPB8S5L0ZEG2ZAZF9V4TNJJNO1D9U9JU7B264QZ\
|
||||
5GLHC3Q0Y3BTECGTI8GRENQ2FV4HSEZKPM9OG302KLSY9MBCSOO0FN229AST84TT87LYWOOS71C\
|
||||
54RPJ9RTO9875Z9DE3HPH89EW5I3SV219O04UU09A4KME7DD7IH49ABO79NR4EXFX1VLL4YOHSA\
|
||||
7AHD1LS5YKZ66F4UPG0RCBGG000000000000000000000000000000000000000000000000000\
|
||||
000000000000000000000000000000000000000000000000000000000000000000000000000
|
||||
"""
|
||||
|
||||
// MARK: - Basic arithmetic
|
||||
|
||||
func testDivision() {
|
||||
let num1 = BigUInt("18446744073709551616")!
|
||||
let den1 = BigUInt(123)
|
||||
let expected1 = BigUInt(UInt64(149973529054549200))
|
||||
XCTAssertEqual(num1 / den1, expected1)
|
||||
|
||||
let num2 = BigUInt.pow(BigUInt(10), 100)
|
||||
let den2: BigUInt = 3
|
||||
let expected2: BigUInt = BigUInt(String(repeating: "3", count: 100))!
|
||||
let actual2 = num2 / den2
|
||||
XCTAssertEqual(actual2, expected2)
|
||||
|
||||
let num3 = BigUInt.pow(BigUInt(10), 97)
|
||||
let den3: BigUInt = BigUInt("33333333333333333333")!
|
||||
let expected3: BigUInt = BigUInt("300000000000000000003000000000000000000030000000000000000000300000000000000000")!
|
||||
let actual3 = num3 / den3
|
||||
XCTAssertEqual(actual3, expected3)
|
||||
|
||||
let foo = BigUInt("12345678901234567890123456789012345678901234567890123456789012345678901234567890")!
|
||||
let bar = BigUInt("351235231535161613134135135135")!
|
||||
let baz = foo / bar
|
||||
XCTAssertEqual(baz, BigUInt("35149318157164029153358504918339691272847595997760")!)
|
||||
|
||||
XCTAssertNotNil(BigUInt(exactly: 2.4e39))
|
||||
XCTAssertNotNil(BigUInt(exactly: 1e38))
|
||||
XCTAssertEqual(BigUInt(2.4e39) / BigUInt(1e38), BigUInt(24))
|
||||
|
||||
for _ in 0 ..< 100 {
|
||||
let expected = BigUInt(Float64.random(in: 0x1p64 ... 0x1p255))
|
||||
let divisor = BigUInt(Float64.random(in: 0x1p64 ... 0x1p128))
|
||||
let (quotient, remainder) = expected.quotientAndRemainder(dividingBy: divisor)
|
||||
let actual = divisor * quotient + remainder
|
||||
XCTAssertEqual(quotient, expected / divisor)
|
||||
XCTAssertEqual(remainder, expected % divisor)
|
||||
XCTAssertEqual(
|
||||
actual, expected,
|
||||
"""
|
||||
## FAILURE ##
|
||||
~~~~~~~~~~~~~
|
||||
actual: \(actual)
|
||||
!= expected: \(expected)
|
||||
~~~~~~~~~~~~~
|
||||
divisor: \(divisor)
|
||||
* quotient: \(quotient)
|
||||
+ remainder: \(remainder)
|
||||
~~~~~~~~~~~~~
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
func testFactorial() {
|
||||
var expectedNumber: BigUInt?
|
||||
var actualNumber: BigUInt!
|
||||
var actualString: String!
|
||||
|
||||
measure {
|
||||
expectedNumber = BigUInt(Self.descriptionFactorial512_radix36, radix: 36)
|
||||
actualNumber = BigUInt.fac(512)
|
||||
actualString = String(actualNumber, radix: 36, uppercase: true)
|
||||
}
|
||||
|
||||
XCTAssertEqual(actualNumber, expectedNumber)
|
||||
XCTAssertEqual(actualString, Self.descriptionFactorial512_radix36)
|
||||
|
||||
XCTAssertEqual(BigUInt.fac(0), 1)
|
||||
XCTAssertEqual(BigUInt.fac(1), 1)
|
||||
XCTAssertEqual(BigUInt.fac(2), 2)
|
||||
XCTAssertEqual(BigUInt.fac(3), 6)
|
||||
XCTAssertEqual(BigUInt.fac(4), 24)
|
||||
XCTAssertEqual(BigUInt.fac(5), 120)
|
||||
XCTAssertEqual(BigUInt.fac(6), 720)
|
||||
XCTAssertEqual(BigUInt.fac(7), 5040)
|
||||
XCTAssertEqual(BigUInt.fac(8), 40320)
|
||||
XCTAssertEqual(BigUInt.fac(9), 362880)
|
||||
}
|
||||
|
||||
func testMath() {
|
||||
let foo = BigUInt.pow(10, 20)
|
||||
let bar = BigUInt("1234567890123456789012345678901234567890")!
|
||||
|
||||
let baz = foo + bar
|
||||
|
||||
XCTAssertEqual(baz, BigUInt("1234567890123456789112345678901234567890")!)
|
||||
|
||||
let fooz = foo >> BigUInt(10)
|
||||
XCTAssertEqual(fooz, foo / 1024)
|
||||
|
||||
let barz = BigUInt(1) << 64
|
||||
XCTAssertEqual(barz, BigUInt(UInt64.max) + 1)
|
||||
}
|
||||
|
||||
func testTrailingZeroCount() {
|
||||
let foo = BigUInt(1) << 300
|
||||
XCTAssertEqual(foo.trailingZeroBitCount, 300)
|
||||
|
||||
let bar = (BigUInt(1) << 300) + 0b101000
|
||||
XCTAssertEqual(bar.trailingZeroBitCount, 3)
|
||||
}
|
||||
|
||||
// MARK: - Comparing and hashing
|
||||
|
||||
func testComparable() {
|
||||
let foo = BigUInt("1234567890123456789012345678901234567890")!
|
||||
let bar = foo * foo
|
||||
|
||||
XCTAssertLessThan(foo, bar)
|
||||
XCTAssertFalse(foo < foo)
|
||||
XCTAssertFalse(bar < bar)
|
||||
XCTAssertFalse(foo > foo)
|
||||
XCTAssertFalse(bar > bar)
|
||||
XCTAssertGreaterThan(bar, foo)
|
||||
}
|
||||
|
||||
func testHashable() {
|
||||
let foo = BigInt("1234567890123456789012345678901234567890")!
|
||||
let bar = BigInt("1234567890123456789112345678901234567890")!
|
||||
let baz: BigInt = 153
|
||||
|
||||
let dict = [foo: "Hello", bar: "World", baz: "!"]
|
||||
let hash = foo.hashValue
|
||||
print(hash)
|
||||
|
||||
XCTAssertEqual(dict[foo]!, "Hello")
|
||||
XCTAssertEqual(dict[bar]!, "World")
|
||||
}
|
||||
|
||||
func testClampingConversion() {
|
||||
XCTAssertEqual(BigUInt(clamping: UInt64.max), BigUInt(UInt64(18446744073709551615)))
|
||||
}
|
||||
|
||||
// MARK: - Converting to/from textual representations
|
||||
|
||||
func testCodable() throws {
|
||||
let lowerBound = BigUInt("0")!
|
||||
let upperBound = BigUInt("+1234567890123456789012345678901234567890")!
|
||||
let expectedRange: Range<BigUInt> = lowerBound ..< upperBound
|
||||
|
||||
let encoder = JSONEncoder()
|
||||
let decoder = JSONDecoder()
|
||||
let data = try encoder.encode(expectedRange)
|
||||
let actualRange = try decoder.decode(Range<BigUInt>.self, from: data)
|
||||
|
||||
XCTAssertEqual(actualRange, expectedRange)
|
||||
}
|
||||
|
||||
func testCustomStringConvertible() {
|
||||
XCTAssertEqual("\(BigUInt(UInt64.min) + 0)", "0")
|
||||
XCTAssertEqual("\(BigUInt(UInt64.min) + 1)", "1")
|
||||
XCTAssertEqual("\(BigUInt(UInt64.min) + 2)", "2")
|
||||
|
||||
XCTAssertEqual("\(BigUInt(UInt64.max) - 2)", "18446744073709551613")
|
||||
XCTAssertEqual("\(BigUInt(UInt64.max) - 1)", "18446744073709551614")
|
||||
XCTAssertEqual("\(BigUInt(UInt64.max) + 0)", "18446744073709551615")
|
||||
XCTAssertEqual("\(BigUInt(UInt64.max) + 1)", "18446744073709551616")
|
||||
XCTAssertEqual("\(BigUInt(UInt64.max) + 2)", "18446744073709551617")
|
||||
|
||||
XCTAssertEqual("\(BigUInt(Int64.max) - 2)", "9223372036854775805")
|
||||
XCTAssertEqual("\(BigUInt(Int64.max) - 1)", "9223372036854775806")
|
||||
XCTAssertEqual("\(BigUInt(Int64.max) + 0)", "9223372036854775807")
|
||||
XCTAssertEqual("\(BigUInt(Int64.max) + 1)", "9223372036854775808")
|
||||
XCTAssertEqual("\(BigUInt(Int64.max) + 2)", "9223372036854775809")
|
||||
|
||||
XCTAssertEqual("\(+(BigUInt(1) << 1023) - 1)", Self.descriptionInt1024Max)
|
||||
}
|
||||
|
||||
func testLosslessStringConvertible() {
|
||||
XCTAssertNil(BigUInt(""))
|
||||
XCTAssertNil(BigUInt("+"))
|
||||
XCTAssertNil(BigUInt("A"))
|
||||
XCTAssertNil(BigUInt(" 0"))
|
||||
XCTAssertNil(BigUInt("0 "))
|
||||
|
||||
XCTAssertEqual(BigUInt(UInt64.min) + 0, BigUInt("0"))
|
||||
XCTAssertEqual(BigUInt(UInt64.min) + 1, BigUInt("1"))
|
||||
XCTAssertEqual(BigUInt(UInt64.min) + 2, BigUInt("2"))
|
||||
|
||||
XCTAssertEqual(BigUInt(UInt64.max) - 2, BigUInt("18446744073709551613"))
|
||||
XCTAssertEqual(BigUInt(UInt64.max) - 1, BigUInt("18446744073709551614"))
|
||||
XCTAssertEqual(BigUInt(UInt64.max) + 0, BigUInt("18446744073709551615"))
|
||||
XCTAssertEqual(BigUInt(UInt64.max) + 1, BigUInt("18446744073709551616"))
|
||||
XCTAssertEqual(BigUInt(UInt64.max) + 2, BigUInt("18446744073709551617"))
|
||||
|
||||
XCTAssertEqual(BigUInt(Int64.max) - 2, BigUInt("9223372036854775805"))
|
||||
XCTAssertEqual(BigUInt(Int64.max) - 1, BigUInt("9223372036854775806"))
|
||||
XCTAssertEqual(BigUInt(Int64.max) + 0, BigUInt("9223372036854775807"))
|
||||
XCTAssertEqual(BigUInt(Int64.max) + 1, BigUInt("9223372036854775808"))
|
||||
XCTAssertEqual(BigUInt(Int64.max) + 2, BigUInt("9223372036854775809"))
|
||||
|
||||
XCTAssertEqual(+(BigUInt(1) << 1023) - 1, BigUInt(Self.descriptionInt1024Max))
|
||||
}
|
||||
|
||||
func testRadicesAndNumerals() {
|
||||
for radix in 2 ... 36 {
|
||||
for uppercase in [false, true] {
|
||||
for _ in 0 ..< 100 {
|
||||
let expectedNumber = BigUInt(UInt.random(in: .min ... .max))
|
||||
let expectedString = String(expectedNumber,
|
||||
radix: radix,
|
||||
uppercase: uppercase)
|
||||
let actualNumber = BigUInt(expectedString, radix: radix)
|
||||
XCTAssertEqual(actualNumber, expectedNumber)
|
||||
if radix == 10 {
|
||||
let actualString = expectedNumber.description
|
||||
XCTAssertEqual(actualString, expectedString)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Converting from floating-point binary types
|
||||
|
||||
func testBinaryFloatingPoint<T>(_ type: T.Type) where T: BinaryFloatingPoint {
|
||||
var expected = BigUInt(T.greatestFiniteMagnitude.significandBitPattern)
|
||||
expected |= BigUInt(1) << T.significandBitCount
|
||||
expected <<= T.greatestFiniteMagnitude.exponent
|
||||
expected >>= T.significandBitCount
|
||||
|
||||
XCTAssertEqual(BigUInt(exactly: +T.greatestFiniteMagnitude), +expected)
|
||||
XCTAssertEqual(BigUInt(+T.greatestFiniteMagnitude), +expected)
|
||||
|
||||
XCTAssertNil(BigUInt(exactly: +T.infinity))
|
||||
|
||||
XCTAssertNil(BigUInt(exactly: +T.leastNonzeroMagnitude))
|
||||
XCTAssertEqual(BigUInt(+T.leastNonzeroMagnitude), 0)
|
||||
|
||||
XCTAssertNil(BigUInt(exactly: +T.leastNormalMagnitude))
|
||||
XCTAssertEqual(BigUInt(+T.leastNormalMagnitude), 0)
|
||||
|
||||
XCTAssertNil(BigUInt(exactly: T.nan))
|
||||
XCTAssertNil(BigUInt(exactly: T.signalingNaN))
|
||||
|
||||
XCTAssertNil(BigUInt(exactly: +T.pi))
|
||||
XCTAssertEqual(BigUInt(+T.pi), +3)
|
||||
|
||||
XCTAssertNil(BigUInt(exactly: +T.ulpOfOne))
|
||||
XCTAssertEqual(BigUInt(+T.ulpOfOne), 0)
|
||||
|
||||
XCTAssertEqual(BigUInt(exactly: +T.zero), 0)
|
||||
XCTAssertEqual(BigUInt(+T.zero), 0)
|
||||
}
|
||||
|
||||
func testBinaryFloatingPoint() {
|
||||
testBinaryFloatingPoint(Float32.self)
|
||||
testBinaryFloatingPoint(Float64.self)
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
testBinaryFloatingPoint(Float80.self)
|
||||
#endif
|
||||
|
||||
for _ in 0 ..< 100 {
|
||||
let small = Float32.random(in: 0 ... +10)
|
||||
XCTAssertEqual(BigUInt(small), BigUInt(Int64(small)))
|
||||
|
||||
let large = Float32.random(in: 0 ... +0x1p23)
|
||||
XCTAssertEqual(BigUInt(large), BigUInt(Int64(large)))
|
||||
}
|
||||
|
||||
for _ in 0 ..< 100 {
|
||||
let small = Float64.random(in: 0 ... +10)
|
||||
XCTAssertEqual(BigUInt(small), BigUInt(Int64(small)))
|
||||
|
||||
let large = Float64.random(in: -0x1p52 ... +0x1p52)
|
||||
XCTAssertEqual(BigInt(large), BigInt(Int64(large)))
|
||||
}
|
||||
|
||||
#if (arch(i386) || arch(x86_64)) && !os(Windows) && !os(Android)
|
||||
for _ in 0 ..< 100 {
|
||||
let small = Float80.random(in: 0 ... +10)
|
||||
XCTAssertEqual(BigUInt(small), BigUInt(Int64(small)))
|
||||
|
||||
let large = Float80.random(in: 0 ..< +0x1p63)
|
||||
XCTAssertEqual(BigUInt(large), BigUInt(Int64(large)))
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user