Author SHA1 Message Date
Stephen Canon 0098c438eb Merge pull request #277 from gwynne/biginteger
Update BigInteger branch from main
2024-01-10 13:55:22 -05:00
Gwynne Raskind 349fdf1e01 Add preliminary version of BigUInt 2023-12-26 11:12:49 -06:00
Gwynne Raskind 0d48ff5a98 Repair BigInt module after merge 2023-12-25 22:44:32 -06:00
Gwynne Raskind 1c90bdc9a9 Merge branch 'main' into biginteger 2023-12-25 22:31:33 -06:00
Stephen Canon fd9722e609 Merge pull request #84 from rothomp3/BigInt
Arbitrary-precision BigInt preliminary work
2022-10-28 15:40:10 -04:00
Stephen Canon f11ce9b248 Merge branch 'biginteger' into BigInt 2022-10-28 15:39:47 -04:00
Robert Thompson 935eac199c Merge pull request #7 from benrimmington/BigInt
[BigInt] Rename module
2020-06-11 15:13:18 -04:00
Ben Rimmington 2f60891517 [BigInt] Rename module
See also: apple/swift-numerics#97
2020-04-24 12:39:49 +01:00
Robert Thompson 5ea7711e02 Probably a slightly faster way to get trailingZeroBitCOunt 2020-02-19 15:15:42 -05:00
Robert Thompson b74c1ce133 Fix trailingZeroBitCount as per @nixberg
Also add a couple tests for it
2020-02-14 16:23:37 -05:00
Robert Thompson cd88f161eb Fix two tests for arm32, should all pass now 2020-01-29 10:48:46 -05:00
Robert Thompson aaeb9029e9 Another fix for conversion of multi-word Ints 2020-01-29 10:42:52 -05:00
Robert Thompson 52e7e70caf Actual fix for multi-word integer types 2020-01-29 10:07:34 -05:00
Robert Thompson caeeaaa9dd Another fix for arm32 and actually for anything with multi-word ints
UInt64, Int64, etc have more than one word on 32-bit architectures
2020-01-29 09:55:10 -05:00
Robert Thompson cc5f7e5d18 Apparently the @testable was only working in Xcode 2020-01-28 17:55:39 -05:00
Robert Thompson feeac39506 Whoops, this is better 2020-01-28 17:53:23 -05:00
Robert Thompson 19951768df Another case where we'd get wrong negatives possibly 2020-01-28 17:51:45 -05:00
Robert Thompson 87900161d6 Normalize the remainder! 2020-01-28 17:36:55 -05:00
Robert Thompson 6e0f0094dc fix tests compiling on arm32 2020-01-28 16:09:32 -05:00
Robert Thompson 7d6e5cda3e Clean up division a bit more 2020-01-28 16:02:30 -05:00
Robert Thompson e4f5257d0a fix division
Re-write _findQhat from scratch, add check for division by single digit
number in _div
2020-01-28 14:05:22 -05:00
Robert Thompson 9e1a1f5e8a Merge branch 'BigInt' of github.com:rothomp3/swift-numerics into BigInt 2020-01-27 12:31:33 -05:00
Robert Thompson 7026eb4085 more tests for division 2020-01-27 12:31:26 -05:00
Robert Thompson 1a29830c82 Merge pull request #6 from benrimmington/BigInt
[BigIntTests] Use generic testBinaryFloatingPoint
2020-01-27 12:17:45 -05:00
Ben Rimmington 5919d3f48f [BigIntTests] Use generic testBinaryFloatingPoint 2020-01-27 15:17:43 +00:00
Robert Thompson e3d01dd680 First step to increasing test coverage 2020-01-22 10:16:01 -05:00
Robert Thompson 90d5ddd1f6 Fix failing tests (@benrimminton: it turned out simple)
If the last computed digit of a BinaryFloatingPoint source is > Int.max,
we need to add an extra zero digit to the end so we're not negative!
2020-01-21 16:59:28 -05:00
Robert Thompson e41c631052 Merge pull request #5 from benrimmington/BigInt
[BigInt] Add tests for floating-point conversions
2020-01-21 16:49:41 -05:00
Ben Rimmington 6e85aa2bbd [BigInt] Revert the BinaryFloatingPoint conversion 2020-01-21 19:47:19 +00:00
Ben Rimmington ceee280ebe [BigIntTests] Don't use the CLongDouble typealias 2020-01-21 18:09:39 +00:00
Ben Rimmington 3501fa7c61 [BigInt] Restore precondition message for inf/nan 2020-01-21 17:30:47 +00:00
Ben Rimmington ca75d2d124 [BigInt] Move pow(_:_:) into test-only extension 2020-01-21 16:24:51 +00:00
Ben Rimmington ffdaf86868 [BigIntTests] Change fac(BigInt(512)) to BigInt.fac(512) 2020-01-21 13:30:21 +00:00
Ben Rimmington bf9afea2eb [BigIntTests] Add testFloatingPoint_signalingNaN() 2020-01-21 08:36:48 +00:00
Ben Rimmington 4c425513cd [BigIntTests] Use fac(_:) to test Strideable 2020-01-20 13:05:49 +00:00
Ben Rimmington fc7b3bf44f [BigIntTests] Update expected descriptions 2020-01-20 11:48:46 +00:00
Ben Rimmington 0dee6d0927 [BigIntTests] Move other test methods 2020-01-20 11:05:12 +00:00
Ben Rimmington cfc63e8adc [BigIntTests] Move testFloatingPoint_...() methods 2020-01-20 10:30:16 +00:00
Ben Rimmington 01c30961ef [BigIntTests] Move the typealias of CLongDouble 2020-01-19 20:31:22 +00:00
Ben Rimmington 05a45984d9 [BigInt] Update signum(), add testSignum() 2020-01-19 19:48:07 +00:00
Ben Rimmington cfc2cd7c97 [BigIntTests] Add measure {} to testFactorial() 2020-01-19 12:32:11 +00:00
Ben Rimmington 98023c3575 [BigInt] Combine *= and << into simpler <<= 2020-01-19 10:31:39 +00:00
Ben Rimmington 506ea36331 [BigIntTests] Update testFloatingPoint_random() 2020-01-19 09:37:20 +00:00
Ben Rimmington 1b733de54a [BigInt] Fix initializers with BinaryFloatingPoint 2020-01-18 19:44:27 +00:00
Ben Rimmington 937c292898 [BigIntTests] Add testFloatingPoint_...() methods
The testFloatingPoint_greatestFiniteMagnitude() method currently fails.
2020-01-18 19:38:05 +00:00
Robert Thompson 49121f353a Merge pull request #4 from benrimmington/BigInt
[BigIntTests] Add min and max Int1024 descriptions
2020-01-17 14:23:20 -05:00
Ben Rimmington e632de88c4 [BigIntTests] Add testFactorial() 2020-01-17 13:51:21 +00:00
Ben Rimmington b03af80076 [BigInt] Change self = -self to self.negate() 2020-01-17 07:33:36 +00:00
Ben Rimmington 6f4374cd99 [BigIntTests] Add min and max Int1024 descriptions 2020-01-17 07:32:52 +00:00
Robert Thompson d36d9ce02e Remove superfluous CustomStringConvertible impl 2020-01-16 17:08:52 -05:00
Robert Thompson fac716fdb2 Fix implementation of <
Previously, all BigInts were less than themselves. This is no longer
true. Discovered thanks to @lorentey and @benrimmington re: discussion
on explicit implementation of `!=`.
2020-01-16 15:15:37 -05:00
Robert Thompson 7ca51a3e50 normalize words in the BinaryInteger bitPattern init
as per @lorentey
2020-01-16 14:25:46 -05:00
Robert Thompson 1ddbbfe0d1 Rename internal init as per @lorentey 2020-01-16 14:24:24 -05:00
Robert Thompson eab5a94499 Merge pull request #3 from benrimmington/BigInt
[BigInt] Update tests and SignedNumeric operator
2020-01-16 14:19:55 -05:00
Ben Rimmington a6ecb7442a [BigIntTests] Update testRadicesAndNumerals() 2020-01-16 14:50:19 +00:00
Ben Rimmington 2410717a17 [BigInt] Update the SignedNumeric prefix operator 2020-01-16 13:12:29 +00:00
Ben Rimmington 7ae61f775b [BigIntTests] Update testLosslessStringConvertible 2020-01-16 13:04:39 +00:00
Ben Rimmington fe212356fd [BigIntTests] Rename testRandomDescriptions() 2020-01-16 12:40:02 +00:00
Ben Rimmington 830927ecbb [BigIntTests] Rewrite testMinMaxDescriptions() 2020-01-16 12:19:33 +00:00
Robert Thompson fd8049e481 remove debugging code from test 2020-01-15 15:25:11 -05:00
Robert Thompson 0b121fd774 Fix failing tests (@benrimmington)
We were not correctly handling the case where two single-word operands
added up to a number > Int.max. Also, negate (and `-`) was not removing
excess words, resulting in identical numbers not comparing equal!
2020-01-15 15:13:58 -05:00
Robert Thompson 72f1cb3554 Merge branch 'BigInt' of github.com:rothomp3/swift-numerics into BigInt 2020-01-15 14:15:36 -05:00
Robert Thompson 0e58379b4f explicitly call out TAOCP by Knuth 2020-01-15 14:15:27 -05:00
Robert Thompson ddaf8be1a2 Merge pull request #2 from benrimmington/BigInt
[BigInt] Update LosslessStringConvertible, etc.
2020-01-15 14:07:37 -05:00
Ben Rimmington 9ddc664ef1 [BigIntTests] Remove messages from XCTAssert calls 2020-01-15 06:51:21 +00:00
Ben Rimmington b39dd05db3 [BigIntTests] Update the testExample() method 2020-01-15 06:44:41 +00:00
Ben Rimmington 1cb69383a5 [BigIntTests] Wrap to 80 characters 2020-01-15 03:53:16 +00:00
Ben Rimmington c9d72fc3ae [BigIntTests] Trim trailing whitespace 2020-01-15 03:34:14 +00:00
Ben Rimmington 4ec520a726 [BigIntTests] Update the testCodable() method
Top-level JSON fragments might fail on Linux, so encode Range<BigInt> instead.

<https://bugs.swift.org/browse/SR-6163>
2020-01-15 03:30:50 +00:00
Ben Rimmington 8c378528de [BigInt] Update the Codable conformance 2020-01-15 00:59:46 +00:00
Ben Rimmington 3cf0b0cf74 [BigInt] Update the LosslessStringConvertible init
This performs 6x faster (measured with a 1000-digit string).

But it doesn't fix the testMinMaxDescriptions() failures.
2020-01-15 00:47:04 +00:00
Ben Rimmington f6a3d2d4e4 [BigIntTests] Add testMinMaxDescriptions() method
This currently fails for:

BigInt(Int64.min) - 2
BigInt(Int64.min) - 1
BigInt(Int64.max) + 1
BigInt(Int64.max) + 2
2020-01-15 00:17:17 +00:00
Robert Thompson 036ab5fe94 Conform to Codable with default implementation
Since we have only a single stored property which itself already
conforms to `Codable`, there's no need to go down the rabbit hole of
explicitly implementing it. If someone wants to do it to produce a more
human-readable JSON (eg, as a string instead of an array of integers),
then you're welcome to.
2020-01-14 15:07:08 -05:00
Robert Thompson 7c6e2ce0d8 Explicitly implement public mutating func negate()
As per the TODO put in by @benrimmington. I'm not 100% sure this is
actually better than the default implementation provided by
`SignedNumeric`, but there's a chance it is.
2020-01-14 15:00:38 -05:00
Robert Thompson 3a4cc1c623 Merge pull request #1 from benrimmington/BigInt
[BigInt] Reorganize into extensions by conformance
2020-01-14 14:47:02 -05:00
Ben Rimmington 4d7e4e9b97 [BigInt] Rename private _findQhat method 2020-01-14 04:44:44 +00:00
Ben Rimmington 3c916262e0 [BigInt] Update bitWidth and magnitude properties 2020-01-14 02:46:47 +00:00
Ben Rimmington 831f06ac78 [BigInt] Add the MARK and TODO comments 2020-01-14 02:44:38 +00:00
Ben Rimmington d15400e6ab [BigInt] Add the Words typealias 2020-01-14 02:39:59 +00:00
Ben Rimmington 5be3b4e526 [BigInt] Move the BinaryInteger methods 2020-01-14 02:38:53 +00:00
Ben Rimmington acd8568864 [BigInt] Move the BinaryInteger operators 2020-01-14 02:36:23 +00:00
Ben Rimmington 11d5225f3b [BigInt] Move the BinaryInteger properties 2020-01-14 02:26:50 +00:00
Ben Rimmington 19d3491df4 [BigInt] Move the BinaryInteger initializers 2020-01-14 02:25:37 +00:00
Ben Rimmington 819ebd90c4 [BigInt] Move the SignedNumeric conformance 2020-01-14 02:16:00 +00:00
Ben Rimmington 5b84051f2a [BigInt] Move the Numeric conformance 2020-01-14 02:14:30 +00:00
Ben Rimmington cb5e7f3c7a [BigInt] Move the AdditiveArithmetic conformance 2020-01-14 02:09:45 +00:00
Ben Rimmington 5cb9b95ce8 [BigInt] Move the ExpressibleByIntegerLiteral conformance 2020-01-14 02:05:42 +00:00
Ben Rimmington 5db4a69e57 [BigInt] Move the LosslessStringConvertible conformance 2020-01-14 02:04:16 +00:00
Ben Rimmington 2419741a7c [BigInt] Move the CustomStringConvertible conformance 2020-01-14 02:00:12 +00:00
Ben Rimmington 368caf5b3f [BigInt] Move the Comparable conformance 2020-01-14 01:58:03 +00:00
Ben Rimmington a799618103 [BigInt] Move the Hashable conformance 2020-01-14 01:56:43 +00:00
Ben Rimmington dbf743b314 [BigInt] Move the Equatable conformance 2020-01-14 01:54:58 +00:00
Ben Rimmington 2f40de6195 [BigInt] Move _isNegative and _digits properties 2020-01-14 01:52:01 +00:00
Ben Rimmington 38073d2ab5 [BigInt] Move init(words:) and init(bitPattern:) 2020-01-14 01:49:26 +00:00
Ben Rimmington 2863c44182 [BigInt] Remove the isSigned property 2020-01-14 01:42:43 +00:00
Robert Thompson e490f1fc66 Explicitly implment hash(into:) per @benrimmington feedback
Technically, I believe the auto-generated implementation was already
doing exactly this, since `words` is the only stored property of
`BigInt`. However, it rarely hurts to be explicit.
2020-01-13 14:45:48 -05:00
Robert Thompson 67858690eb Update LosslessStringConvertible initializer
as per further suggestions from @Wildchild9, adding in the removing
leading zeros part I missed.
2019-12-30 16:01:04 -05:00
Robert Thompson cced27a6c0 Missed a spot where things should be alphabetical 2019-12-30 15:50:03 -05:00
Robert Thompson 821fcbd6a4 Update following suggestions from @benrimmington
Includes reformatting to use 2-space indentation and the correct file
headers, among other simplifications.
2019-12-30 15:46:18 -05:00
Robert Thompson b46dcf96c6 oops, change both occurrences of digitsAndDash 2019-12-30 15:13:26 -05:00
Robert ThompsonandBen Rimmington eceae6d7bd Update Sources/BigInt/BigInt.swift
As per benrimmington's excellent suggestion

Co-Authored-By: Ben Rimmington <me@benrimmington.com>
2019-12-30 15:12:20 -05:00
Robert Thompson ac50a90a60 whoops 2019-12-30 10:44:48 -05:00
Robert Thompson 524dc69ae1 slightly refactor LosslessStringConvertible initializer as per PR feedback 2019-12-30 10:41:40 -05:00
Robert Thompson ea2b6f8deb BigInt no longer depends on NumericsShims 2019-12-30 10:33:00 -05:00
Robert Thompson cb56525312 Address PR feedback
Eliminate unnecessary math function calls, and also handle floating
point edge cases better.
2019-12-30 10:33:00 -05:00
Robert Thompson bc2f9fb7c6 Use NumericShims for math functions 2019-12-30 10:33:00 -05:00
Robert Thompson 96d41bcf9f Initial commit of BigInt 2019-12-30 10:33:00 -05:00
12 changed files with 2430 additions and 3 deletions

No files matched your search

+1 -1
View File
@@ -1,4 +1,4 @@
version: 1
builder:
configs:
- documentation_targets: [Numerics, RealModule, ComplexModule]
- documentation_targets: [Numerics, RealModule, ComplexModule, BigIntModule]
+13 -1
View File
@@ -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
View File
@@ -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"],
+1
View File
@@ -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
+810
View File
@@ -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: &quot)
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: &quot)
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
}
}
}
}
+751
View File
@@ -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: &quot)
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: &quot)
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
}
}
}
}
+16
View File
@@ -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)
+3
View File
@@ -0,0 +1,3 @@
# Arbitrary-precision integers
This module provides a `BigInt` type.
+1
View File
@@ -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)
+1
View File
@@ -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
+460
View File
@@ -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
}
}
+360
View File
@@ -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
}
}