数学

模运算和位运算

导入

.package(url: "https://github.com/DavidSkrundz/Math.git", .upToNextMinor(from: "1.4.0"))

随机数

声明了 FixedWidthInteger 自带的四个 random() 函数

ModularOperations

声明了模运算操作

func modulo(_ modulo: Self) -> Self
func adding(_ other: Self, modulo: Self) -> Self
func subtracting(_ other: Self, modulo: Self) -> Self
func multiplying(_ other: Self, modulo: Self) -> Self
func exponentiating(by exponent: Self, modulo: Self) -> Self
func inverse(modulo: Self) -> Self?
func gcdDecomposition(_ other: Self) -> (gcd: Self, selfCount: Self, otherCount: Self)

FloatingPointBinaryInteger 定义了 modulo

BinaryInteger where Self: ModularOperations 定义了 exponentiating (求幂) 和 inverse (求逆)

FixedWidthInteger 实现了剩余的函数

Int, Int8, Int16, Int32, Int64, UInt, UInt8, UInt16, UInt32, 和 UInt64 都遵循 ModularOperations 协议

BinaryInteger

位旋转

static func >>> <RHS: BinaryInteger>(lhs: Self, rhs: RHS) -> Self
static func <<< <RHS: BinaryInteger>(lhs: Self, rhs: RHS) -> Self

平方根

func sqrt() -> Self

FixedWidthInteger

字节转换

var littleEndianBytes: [UInt8]
var bigEndianBytes: [UInt8]

Array where Element == UInt8 (元素类型为 UInt8 的数组)

字符串转换

var hexString: String

Array where Element: BinaryInteger (元素类型遵循 BinaryInteger 的数组)

位打包/解包

func asBigEndian<T: BinaryInteger>(sourceBits: Int = MemoryLayout<Element>.size * 8, resultBits: Int = MemoryLayout<T>.size * 8) -> [T]
func asLittleEndian<T: BinaryInteger>(sourceBits: Int = MemoryLayout<Element>.size * 8, resultBits: Int = MemoryLayout<T>.size * 8) -> [T]

FiniteFieldInteger

一个用于定义自定义有限域的协议。它实现了 Numeric, Strideable, 和 LosslessStringConvertible

定义一个新的 FiniteFieldInteger

struct F_31: FiniteFieldInteger {
	static var Order = UInt8(31) // Must be prime
	var value: Element = 0
}

已实现的功能

init()
init(_ value: Element)
init(integerLiteral value: Element)
init?(_ description: String)
init?<T>(exactly source: T) where T: BinaryInteger

var description: String

func distance(to other: Self) -> Int
func advanced(by n: Int) -> Self

static func == (lhs: Self, rhs: Self) -> Bool
static func < (lhs: Self, rhs: Self) -> Bool

static func ... (minimum: Self, maximum: Self) -> ClosedRange<Self>

static func + (lhs: Self, rhs: Self) -> Self
static func - (lhs: Self, rhs: Self) -> Self
static func * (lhs: Self, rhs: Self) -> Self
static func / (lhs: Self, rhs: Self) -> Self
static func % (lhs: Self, rhs: Self) -> Self
func exponentiating(by value: Element) -> Self

static func += (lhs: inout Self, rhs: Self)
static func -= (lhs: inout Self, rhs: Self)
static func *= (lhs: inout Self, rhs: Self)
static func /= (lhs: inout Self, rhs: Self)
static func %= (lhs: inout Self, rhs: Self)

BigUInt

一种任意精度无符号整数类型。它遵循 UnsignedIntegerModularOperations, 并且提供 func power<T: BinaryInteger>(of exponent: T) -> BigUInt (计算幂的函数)

BigUIntgcdDecomposition() 只返回有效的 gcd (最大公约数)。 selfCountotherCount 的值没有意义 (并且总是零)

目前没有 BigInt 的实现,所以 Strideable 的一致性来自标准库,这意味着调用 distance(to other: BigUInt)advanced(by n: BigInt) 是不安全的,除非差值在 Int 的范围内