Scoop API

scoop:scoop.math:0.1.0

src/big_integer/big_integer.scoop

Selected production source · src/big_integer/big_integer.scoop

1package scoop.math
3import scoop.map
5import scoop.bytes.ByteOrder
6import scoop.random.Random
8/** An immutable arbitrary-precision signed integer with infinite two's-complement bit semantics. */
9public class BigInteger internal constructor(private val storage: IntegerStorage) :
10 Equals<BigInteger>, Compare<BigInteger>, Hash, ToString,
11 Add<BigInteger, BigInteger>, Sub<BigInteger, BigInteger>, Mul<BigInteger, BigInteger>,
12 Div<BigInteger, BigInteger>, Rem<BigInteger, BigInteger>, UnaryPlus<BigInteger>,
13 UnaryMinus<BigInteger>, Increment<BigInteger>, Decrement<BigInteger> {
14 /** Constructs the exact signed integer. */
15 public constructor(value: Long) : this(IntegerStorage.Small(value)) {}
16 /** Constructs the exact unsigned integer, including values above Long.MAX_VALUE. */
17 public constructor(value: ULong) : this(integerUnsigned(value)) {}
19 internal fun integerStorage(): IntegerStorage = storage
21 /** The numeric sign: -1, 0, or 1. */
22 public val signum: Int get() = integerSign(storage)
23 /** Compares mathematical values. */
24 public override operator fun equals(other: BigInteger): Boolean = integerCompare(storage, other.storage) == 0L
25 /** Returns -1, 0, or 1 in numerical order. */
26 public override operator fun compareTo(other: BigInteger): Long = integerCompare(storage, other.storage)
27 /** Hashes the mathematical integer. */
28 public override fun hash(): Long = integerHash(storage)
29 /** Formats in decimal without redundant leading zeros. */
30 public override fun toString(): String = integerString(storage, 10)
31 /** Formats in radix 2..36 with lowercase digits; an invalid radix throws. */
32 public fun toString(radix: Int): String = integerString(storage, radix)
34 /** Returns the exact sum. */
35 public override operator fun plus(other: BigInteger): BigInteger = BigInteger(integerAdd(storage, other.storage))
36 /** Returns the exact difference. */
37 public override operator fun minus(other: BigInteger): BigInteger = BigInteger(integerSubtract(storage, other.storage))
38 /** Returns the exact product. */
39 public override operator fun times(other: BigInteger): BigInteger = BigInteger(integerMultiply(storage, other.storage))
40 /** Divides toward zero; a zero divisor throws ArithmeticException. */
41 public override operator fun div(other: BigInteger): BigInteger = BigInteger(integerDivide(storage, other.storage)._1)
42 /** Returns the remainder with this value's sign; a zero divisor throws. */
43 public override operator fun rem(other: BigInteger): BigInteger = BigInteger(integerDivide(storage, other.storage)._2)
44 /** Returns this immutable value. */
45 public override operator fun unaryPlus(): BigInteger = this
46 /** Returns the exact negation. */
47 public override operator fun unaryMinus(): BigInteger = BigInteger(integerNegate(storage))
48 /** Returns this value plus one. */
49 public override operator fun inc(): BigInteger = this + BigInteger.ONE
50 /** Returns this value minus one. */
51 public override operator fun dec(): BigInteger = this - BigInteger.ONE
52 /** Returns the nonnegative magnitude. */
53 public fun abs(): BigInteger = if (signum < 0) -this else this
54 /** Returns the smaller value, retaining this instance on equality. */
55 public fun min(other: BigInteger): BigInteger = if (this <= other) this else other
56 /** Returns the larger value, retaining this instance on equality. */
57 public fun max(other: BigInteger): BigInteger = if (this >= other) this else other
58 /** Computes quotient and remainder together; the quotient truncates toward zero. */
59 public fun divideAndRemainder(other: BigInteger): (BigInteger, BigInteger) {
60 val result = integerDivide(storage, other.storage)
61 return (BigInteger(result._1), BigInteger(result._2))
62 }
63 /** Raises to a nonnegative exponent; a negative exponent throws, and 0^0 is one. */
64 public fun pow(exponent: Long): BigInteger = BigInteger(integerPow(storage, exponent))
65 /** Returns floor(sqrt(this)); negative values throw ArithmeticException. */
66 public fun sqrt(): BigInteger = BigInteger(integerSqrt(storage)._1)
67 /** Returns floor(sqrt(this)) and the exact nonnegative remainder. */
68 public fun sqrtAndRemainder(): (BigInteger, BigInteger) {
69 val result = integerSqrt(storage)
70 return (BigInteger(result._1), BigInteger(result._2))
71 }
72 /** Returns the nonnegative greatest common divisor, including gcd(0,0)=0. */
73 public fun gcd(other: BigInteger): BigInteger = BigInteger(integerGcd(storage, other.storage))
74 /** Reduces into [0, modulus); a nonpositive modulus throws ArithmeticException. */
75 public fun mod(modulus: BigInteger): BigInteger = BigInteger(integerMod(storage, modulus.storage))
76 /** Computes a modular power; negative exponents require a modular inverse. */
77 public fun modPow(exponent: BigInteger, modulus: BigInteger): BigInteger = BigInteger(integerModPow(storage, exponent.storage, modulus.storage))
78 /** Returns the modular inverse, or throws for a nonpositive modulus or missing inverse. */
79 public fun modInverse(modulus: BigInteger): BigInteger = BigInteger(integerModInverse(storage, modulus.storage))
81 /** Counts bits after removing redundant sign extension; zero and -1 have length zero. */
82 public fun bitLength(): Long = integerBitLength(storage)
83 /** Counts bits differing from the infinitely extended sign bit. */
84 public fun bitCount(): Long = integerBitCount(storage)
85 /** Returns the lowest set bit, or -1 for zero. */
86 public fun lowestSetBit(): Long = magnitudeLowestBit(integerMagnitude(storage))
87 /** Tests a nonnegative bit position; a negative index throws IllegalArgumentException. */
88 public fun testBit(index: Long): Boolean = integerTestBit(storage, index)
89 /** Sets a nonnegative bit position in the infinite two's-complement representation. */
90 public fun setBit(index: Long): BigInteger = BigInteger(integerChangeBit(storage, index, 0))
91 /** Clears a nonnegative bit position in the infinite two's-complement representation. */
92 public fun clearBit(index: Long): BigInteger = BigInteger(integerChangeBit(storage, index, 1))
93 /** Flips a nonnegative bit position in the infinite two's-complement representation. */
94 public fun flipBit(index: Long): BigInteger = BigInteger(integerChangeBit(storage, index, 2))
95 /** Inverts every bit, including the infinitely extended sign. */
96 public fun inv(): BigInteger = BigInteger(integerSubtract(integerNegate(storage), IntegerStorage.Small(1L)))
97 /** Shifts left without masking the distance; negative distances shift right. */
98 public infix fun shl(distance: Long): BigInteger = BigInteger(integerShift(storage, distance, true))
99 /** Shifts arithmetically right; negative distances shift left. */
100 public infix fun shr(distance: Long): BigInteger = BigInteger(integerShift(storage, distance, false))
101 /** Applies infinite two's-complement AND to both values. */
102 public infix fun and(other: BigInteger): BigInteger = BigInteger(integerBitwise(storage, other.storage, 0))
103 /** Applies infinite two's-complement OR to both values. */
104 public infix fun or(other: BigInteger): BigInteger = BigInteger(integerBitwise(storage, other.storage, 1))
105 /** Applies infinite two's-complement XOR to both values. */
106 public infix fun xor(other: BigInteger): BigInteger = BigInteger(integerBitwise(storage, other.storage, 2))
107 /** Applies infinite two's-complement ANDNOT to both values. */
108 public infix fun andNot(other: BigInteger): BigInteger = BigInteger(integerBitwise(storage, other.storage, 3))
110 /** Returns an independent shortest signed two's-complement byte array; zero is one zero byte. */
111 public fun toByteArray(order: ByteOrder = ByteOrder.BigEndian): Array<Byte> = integerBytes(storage, order, true)
112 /** Returns an independent shortest unsigned magnitude byte array; zero is one zero byte. */
113 public fun toMagnitudeByteArray(order: ByteOrder = ByteOrder.BigEndian): Array<Byte> = integerBytes(storage, order, false)
114 /** Rounds directly to binary32 with nearest-even rounding, allowing infinity. */
115 public fun toFloat(): Float = integerFloat(storage)
116 /** Rounds directly to binary64 with nearest-even rounding, allowing infinity. */
117 public fun toDouble(): Double = integerDouble(storage)
118 /** Takes the low 8 bits and interprets them as Byte. */
119 public fun toByte(): Byte = integerLowBits(storage).toByte()
120 /** Converts exactly; an out-of-range value throws ArithmeticException. */
121 public fun toByteExact(): Byte {
122 if (integerCompare(storage, IntegerStorage.Small(Byte.MIN_VALUE.toLong())) < 0L || integerCompare(storage, IntegerStorage.Small(Byte.MAX_VALUE.toLong())) > 0L) mathOverflow()
123 return toByte()
124 }
125 /** Takes the low 16 bits and interprets them as Short. */
126 public fun toShort(): Short = integerLowBits(storage).toShort()
127 /** Converts exactly; an out-of-range value throws ArithmeticException. */
128 public fun toShortExact(): Short {
129 if (integerCompare(storage, IntegerStorage.Small(Short.MIN_VALUE.toLong())) < 0L || integerCompare(storage, IntegerStorage.Small(Short.MAX_VALUE.toLong())) > 0L) mathOverflow()
130 return toShort()
131 }
132 /** Takes the low 32 bits and interprets them as Int. */
133 public fun toInt(): Int = integerLowBits(storage).toInt()
134 /** Converts exactly; an out-of-range value throws ArithmeticException. */
135 public fun toIntExact(): Int {
136 if (integerCompare(storage, IntegerStorage.Small(Int.MIN_VALUE.toLong())) < 0L || integerCompare(storage, IntegerStorage.Small(Int.MAX_VALUE.toLong())) > 0L) mathOverflow()
137 return toInt()
138 }
139 /** Takes the low 64 bits and interprets them as Long. */
140 public fun toLong(): Long = integerLowBits(storage).toLong()
141 /** Converts exactly; an out-of-range value throws ArithmeticException. */
142 public fun toLongExact(): Long {
143 if (integerCompare(storage, IntegerStorage.Small(Long.MIN_VALUE.toLong())) < 0L || integerCompare(storage, IntegerStorage.Small(Long.MAX_VALUE.toLong())) > 0L) mathOverflow()
144 return toLong()
145 }
146 /** Takes the low 8 bits and interprets them as UByte. */
147 public fun toUByte(): UByte = integerLowBits(storage).toUByte()
148 /** Converts exactly; an out-of-range value throws ArithmeticException. */
149 public fun toUByteExact(): UByte {
150 if (integerCompare(storage, IntegerStorage.Small(0L)) < 0L || integerCompare(storage, IntegerStorage.Small(UByte.MAX_VALUE.toLong())) > 0L) mathOverflow()
151 return toUByte()
152 }
153 /** Takes the low 16 bits and interprets them as UShort. */
154 public fun toUShort(): UShort = integerLowBits(storage).toUShort()
155 /** Converts exactly; an out-of-range value throws ArithmeticException. */
156 public fun toUShortExact(): UShort {
157 if (integerCompare(storage, IntegerStorage.Small(0L)) < 0L || integerCompare(storage, IntegerStorage.Small(UShort.MAX_VALUE.toLong())) > 0L) mathOverflow()
158 return toUShort()
159 }
160 /** Takes the low 32 bits and interprets them as UInt. */
161 public fun toUInt(): UInt = integerLowBits(storage).toUInt()
162 /** Converts exactly; an out-of-range value throws ArithmeticException. */
163 public fun toUIntExact(): UInt {
164 if (integerCompare(storage, IntegerStorage.Small(0L)) < 0L || integerCompare(storage, IntegerStorage.Small(UInt.MAX_VALUE.toLong())) > 0L) mathOverflow()
165 return toUInt()
166 }
167 /** Takes the low 64 bits and interprets them as ULong. */
168 public fun toULong(): ULong = integerLowBits(storage).toULong()
169 /** Converts exactly; an out-of-range value throws ArithmeticException. */
170 public fun toULongExact(): ULong {
171 if (integerCompare(storage, IntegerStorage.Small(0L)) < 0L || integerCompare(storage, integerUnsigned(ULong.MAX_VALUE)) > 0L) mathOverflow()
172 return toULong()
173 }
175 /** Tests primality; certainty must be positive, and the random source must supply independent uniform bits. */
176 public fun isProbablePrime(random: Random, certainty: Int = 100): Boolean {
177 requirePrimeCertainty(certainty)
178 return integerIsPrime(storage, random, certainty)
179 }
180 /** Finds the next larger positive probable prime using the explicit random source. */
181 public fun nextProbablePrime(random: Random, certainty: Int = 100): BigInteger {
182 requirePrimeCertainty(certainty)
183 return BigInteger(integerNextPrime(storage, random, certainty))
184 }
186 /** Constants and exact construction factories. */
187 public companion object {
188 /** The integer zero. */
189 public val ZERO: BigInteger = BigInteger(0L)
190 /** The integer one. */
191 public val ONE: BigInteger = BigInteger(1L)
192 /** The integer two. */
193 public val TWO: BigInteger = BigInteger(2L)
194 /** The integer ten. */
195 public val TEN: BigInteger = BigInteger(10L)
196 /** Parses signed ASCII digits in radix 2..36; malformed text throws NumberFormatException. */
197 public fun parse(text: String, radix: Int = 10): BigInteger = BigInteger(integerRequireParsed(text, radix))
198 /** Returns None only for malformed text; an invalid radix still throws. */
199 public fun parseOrNone(text: String, radix: Int = 10): BigInteger? = integerParse(text, radix).map { value -> BigInteger(value) }
200 /** Copies nonempty signed two's-complement bytes; redundant sign extension is accepted. */
201 public fun fromByteArray(bytes: List<Byte>, order: ByteOrder = ByteOrder.BigEndian): BigInteger = BigInteger(integerFromBytes(bytes, order, true, 0))
202 /** Copies magnitude bytes with sign -1, 0, or 1; zero sign requires zero magnitude. */
203 public fun fromMagnitude(signum: Int, bytes: List<Byte>, order: ByteOrder = ByteOrder.BigEndian): BigInteger = BigInteger(integerFromBytes(bytes, order, false, signum))
204 /** Generates a probable prime of exactly bitLength bits, at least two, using the supplied random source. */
205 public fun probablePrime(bitLength: Long, random: Random, certainty: Int = 100): BigInteger {
206 requirePrimeCertainty(certainty)
207 return BigInteger(integerProbablePrime(bitLength, random, certainty))
208 }
209 }