├── .gitignore
├── LICENSE
├── Makefile
├── README.md
├── bint.lua
├── docs
├── index.html
└── ldoc.css
├── examples
├── bench.lua
├── e.lua
├── factorial.lua
├── fibonacci.lua
├── pi.lua
├── rsa.lua
├── secp256k1.lua
└── simple.lua
├── rockspecs
├── bint-0.5.2-1.rockspec
└── bint-dev-1.rockspec
└── tests.lua
/.gitignore:
--------------------------------------------------------------------------------
1 | *.out
2 | play.lua
3 | *.rock
4 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2020-2024 Eduardo Bart (https://github.com/edubart)
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | ROCKSPEC=rockspecs/bint-0.*.rockspec
2 | LUA?=lua
3 |
4 | test:
5 | $(LUA) tests.lua
6 | $(LUA) examples/simple.lua
7 | $(LUA) examples/fibonacci.lua
8 | $(LUA) examples/factorial.lua
9 | $(LUA) examples/pi.lua
10 | $(LUA) examples/e.lua
11 | $(LUA) examples/rsa.lua
12 | $(LUA) examples/secp256k1.lua
13 |
14 | docs:
15 | ldoc -d docs -f markdown bint.lua
16 |
17 | coverage:
18 | rm -f *.out
19 | lua -lluacov tests.lua
20 | luacov
21 |
22 | clean:
23 | rm -f *.out
24 |
25 | install:
26 | luarocks make --local
27 |
28 | upload:
29 | luarocks upload --api-key=$(LUAROCKS_APIKEY) $(ROCKSPEC)
30 |
31 | .PHONY: test docs coverage clean
32 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Lua Bint
2 |
3 | Small portable arbitrary-precision integer arithmetic library in pure Lua for
4 | computing with large integers.
5 |
6 | Different from most arbitrary-precision integer libraries in pure Lua out there this one
7 | uses an array of lua integers as underlying data-type in its implementation instead of
8 | using strings or large tables, this make it efficient for working with fixed width integers
9 | and to make bitwise operations.
10 |
11 | Bint stands for Big Integer.
12 |
13 | The library implementation was highly inspired by
14 | [tiny-bignum-c](https://github.com/kokke/tiny-bignum-c).
15 |
16 | This library was created to be used in the
17 | [Nelua programming language](https://github.com/edubart/nelua-lang) compiler.
18 | It is successfully used there to handle compile time operations on signed and unsigned integers.
19 |
20 | ## Design goals
21 |
22 | The main design goal of this library is to be small, correct, self contained and use few
23 | resources while retaining acceptable performance and feature completeness.
24 |
25 | The library is designed to follow recent Lua integer semantics, this means that
26 | integer overflow warps around,
27 | signed integers are implemented using two-complement arithmetic rules,
28 | integer division operations rounds towards minus infinity,
29 | any mixed operations with float numbers promotes the value to a float,
30 | and the usual division/power operation always promotes to floats.
31 |
32 | The library is designed to be possible to work with only unsigned integer arithmetic
33 | when using the proper methods.
34 |
35 | All the lua arithmetic operators (+, -, *, //, /, %) and bitwise operators (&, |, ~, <<, >>)
36 | are implemented as metamethods.
37 |
38 | The integer size must be fixed in advance and the library is designed to be more efficient when
39 | working with integers of sizes between 64-4096 bits. If you need to work with really huge numbers
40 | without size restrictions then use another library. This choice has been made to have more efficiency
41 | in that specific size range.
42 |
43 | ## Features
44 |
45 | * Small, simple and self contained.
46 | * Efficient (for a pure Lua integer library).
47 | * Works with fixed width integers.
48 | * Follows Lua 5.3+ integer arithmetic semantics by default.
49 | * All integer overflows wraps around.
50 | * Can work with large integer widths with reasonable speed (such as 1024bit integers).
51 | * Implements all lua arithmetic metamethods.
52 | * Provide methods to work with unsigned arithmetic only.
53 | * Supports signed integers by default using two-complement arithmetic rules on unsigned operations.
54 | * Allow to mix any operation with lua numbers, promoting to lua floats where needed.
55 | * Can perform bitwise operations.
56 |
57 | ## Documentation
58 |
59 | The full API reference and documentation can be viewed in the
60 | [documentation website](https://edubart.github.io/lua-bint/).
61 |
62 | ## Install
63 |
64 | You can use luarocks to install quickly:
65 |
66 | ```bash
67 | luarocks install bint
68 | ```
69 |
70 | Or just copy the `bint.lua` file, the library is self contained in this single file with no dependencies.
71 |
72 | ## Examples
73 |
74 | ```lua
75 | local bint = require 'bint'(256) -- use 256 bits integers
76 | local x = bint(1)
77 | x = x << 128
78 | print(x) -- outputs: 340282366920938463463374607431768211456
79 | assert(tostring(x) == '340282366920938463463374607431768211456')
80 | ```
81 |
82 | For more usage examples check the
83 | [examples directory](https://github.com/edubart/lua-bint/tree/master/examples).
84 |
85 | Some interesting examples there:
86 |
87 | * [factorial.lua](https://github.com/edubart/lua-bint/blob/master/examples/factorial.lua) - calculate factorial of 100
88 | * [fibonacci.lua](https://github.com/edubart/lua-bint/blob/master/examples/fibonacci.lua) - calculate the 1001th number of the Fibonacci sequence
89 | * [pi.lua](https://github.com/edubart/lua-bint/blob/master/examples/pi.lua) - calculate the first 100 digits of Pi
90 | * [e.lua](https://github.com/edubart/lua-bint/blob/master/examples/e.lua) - calculate the first 100 digits of Euler's number
91 | * [rsa.lua](https://github.com/edubart/lua-bint/blob/master/examples/rsa.lua) - simple RSA example for encrypting/decrypting messages
92 | * [secp256k1.lua](https://github.com/edubart/lua-bint/blob/master/examples/secp256k1.lua) - simple Secp256k1 elliptic curve example for encrypting/decrypting/signing messages
93 |
94 | ## Tests
95 |
96 | To check if everything is working as expected under your machine run `lua tests.lua` or `make test`.
97 |
98 | ## Limitations
99 |
100 | It is intended only to be used in Lua 5.3+.
101 | The library can theoretically be backported to Lua 5.1/LuaJIT but there is no plan at the moment.
102 | The integer size is limited in advance, this is a design choice.
103 |
104 | ## License
105 |
106 | MIT License
107 |
--------------------------------------------------------------------------------
/bint.lua:
--------------------------------------------------------------------------------
1 | --[[--
2 | lua-bint - v0.5.2 - 30/Oct/2024
3 | Eduardo Bart - edub4rt@gmail.com
4 | https://github.com/edubart/lua-bint
5 |
6 | Small portable arbitrary-precision integer arithmetic library in pure Lua for
7 | computing with large integers.
8 |
9 | Different from most arbitrary-precision integer libraries in pure Lua out there this one
10 | uses an array of lua integers as underlying data-type in its implementation instead of
11 | using strings or large tables, this make it efficient for working with fixed width integers
12 | and to make bitwise operations.
13 |
14 | ## Design goals
15 |
16 | The main design goal of this library is to be small, correct, self contained and use few
17 | resources while retaining acceptable performance and feature completeness.
18 |
19 | The library is designed to follow recent Lua integer semantics, this means that
20 | integer overflow warps around,
21 | signed integers are implemented using two-complement arithmetic rules,
22 | integer division operations rounds towards minus infinity,
23 | any mixed operations with float numbers promotes the value to a float,
24 | and the usual division/power operation always promotes to floats.
25 |
26 | The library is designed to be possible to work with only unsigned integer arithmetic
27 | when using the proper methods.
28 |
29 | All the lua arithmetic operators (+, -, *, //, /, %) and bitwise operators (&, |, ~, <<, >>)
30 | are implemented as metamethods.
31 |
32 | The integer size must be fixed in advance and the library is designed to be more efficient when
33 | working with integers of sizes between 64-4096 bits. If you need to work with really huge numbers
34 | without size restrictions then use another library. This choice has been made to have more efficiency
35 | in that specific size range.
36 |
37 | ## Usage
38 |
39 | First on you should require the bint file including how many bits the bint module will work with,
40 | by calling the returned function from the require, for example:
41 |
42 | ```lua
43 | local bint = require 'bint'(1024)
44 | ```
45 |
46 | For more information about its arguments see @{newmodule}.
47 | Then when you need create a bint, you can use one of the following functions:
48 |
49 | * @{bint.fromuinteger} (convert from lua integers, but read as unsigned integer)
50 | * @{bint.frominteger} (convert from lua integers, preserving the sign)
51 | * @{bint.frombase} (convert from arbitrary bases, like hexadecimal)
52 | * @{bint.fromstring} (convert from arbitrary string, support binary/hexadecimal/decimal)
53 | * @{bint.trunc} (convert from lua numbers, truncating the fractional part)
54 | * @{bint.new} (convert from anything, asserts on invalid integers)
55 | * @{bint.tobint} (convert from anything, returns nil on invalid integers)
56 | * @{bint.parse} (convert from anything, returns a lua number as fallback)
57 | * @{bint.zero}
58 | * @{bint.one}
59 | * `bint`
60 |
61 | You can also call `bint` as it is an alias to `bint.new`.
62 | In doubt use @{bint.new} to create a new bint.
63 |
64 | Then you can use all the usual lua numeric operations on it,
65 | all the arithmetic metamethods are implemented.
66 | When you are done computing and need to get the result,
67 | get the output from one of the following functions:
68 |
69 | * @{bint.touinteger} (convert to a lua integer, wraps around as an unsigned integer)
70 | * @{bint.tointeger} (convert to a lua integer, wraps around, preserves the sign)
71 | * @{bint.tonumber} (convert to lua float, losing precision)
72 | * @{bint.tobase} (convert to a string in any base)
73 | * @{bint.__tostring} (convert to a string in base 10)
74 |
75 | To output a very large integer with no loss you probably want to use @{bint.tobase}
76 | or call `tostring` to get a string representation.
77 |
78 | ## Precautions
79 |
80 | All library functions can be mixed with lua numbers,
81 | this makes easy to mix operations between bints and lua numbers,
82 | however the user should take care in some situations:
83 |
84 | * Don't mix integers and float operations if you want to work with integers only.
85 | * Don't use the regular equal operator ('==') to compare values from this library,
86 | unless you know in advance that both values are of the same primitive type,
87 | otherwise it will always return false, use @{bint.eq} to be safe.
88 | * Don't pass fractional numbers to functions that an integer is expected
89 | * Don't mix operations between bint classes with different sizes as this is not supported, this
90 | will throw assertions.
91 | * Remember that casting back to lua integers or numbers precision can be lost.
92 | * For dividing while preserving integers use the @{bint.__idiv} (the '//' operator).
93 | * For doing power operation preserving integers use the @{bint.ipow} function.
94 | * Configure the proper integer size you intend to work with, otherwise large integers may wrap around.
95 |
96 | ## License
97 |
98 | MIT, see end of file.
99 |
100 | ]]
101 |
102 | -- Returns number of bits of the internal lua integer type.
103 | local function luainteger_bitsize()
104 | local n, i = -1, 0
105 | repeat
106 | n, i = n >> 16, i + 16
107 | until n==0
108 | return i
109 | end
110 |
111 | local math_type = math.type
112 | local math_floor = math.floor
113 | local math_abs = math.abs
114 | local math_ceil = math.ceil
115 | local math_modf = math.modf
116 | local math_mininteger = math.mininteger
117 | local math_maxinteger = math.maxinteger
118 | local math_max = math.max
119 | local math_min = math.min
120 | local string_format = string.format
121 | local table_insert = table.insert
122 | local table_concat = table.concat
123 | local table_unpack = table.unpack
124 |
125 | local memo = {}
126 |
127 | --- Create a new bint module representing integers of the desired bit size.
128 | -- This is the returned function when `require 'bint'` is called.
129 | -- @function newmodule
130 | -- @param bits Number of bits for the integer representation, must be multiple of wordbits and
131 | -- at least 64.
132 | -- @param[opt] wordbits Number of the bits for the internal word,
133 | -- defaults to half of Lua's integer size.
134 | local function newmodule(bits, wordbits)
135 |
136 | local intbits = luainteger_bitsize()
137 | bits = bits or 256
138 | wordbits = wordbits or (intbits // 2)
139 |
140 | -- Memoize bint modules
141 | local memoindex = bits * 64 + wordbits
142 | if memo[memoindex] then
143 | return memo[memoindex]
144 | end
145 |
146 | -- Validate
147 | assert(bits % wordbits == 0, 'bitsize is not multiple of word bitsize')
148 | assert(2*wordbits <= intbits, 'word bitsize must be half of the lua integer bitsize')
149 | assert(bits >= 64, 'bitsize must be >= 64')
150 | assert(wordbits >= 8, 'wordbits must be at least 8')
151 | assert(bits % 8 == 0, 'bitsize must be multiple of 8')
152 |
153 | -- Create bint module
154 | local bint = {}
155 | bint.__index = bint
156 |
157 | --- Number of bits representing a bint instance.
158 | bint.bits = bits
159 |
160 | -- Constants used internally
161 | local BINT_BITS = bits
162 | local BINT_BYTES = bits // 8
163 | local BINT_WORDBITS = wordbits
164 | local BINT_SIZE = BINT_BITS // BINT_WORDBITS
165 | local BINT_WORDMAX = (1 << BINT_WORDBITS) - 1
166 | local BINT_WORDMSB = (1 << (BINT_WORDBITS - 1))
167 | local BINT_LEPACKFMT = '<'..('I'..(wordbits // 8)):rep(BINT_SIZE)
168 | local BINT_MATHMININTEGER, BINT_MATHMAXINTEGER
169 | local BINT_MININTEGER
170 |
171 | --- Create a new bint with 0 value.
172 | function bint.zero()
173 | local x = setmetatable({}, bint)
174 | for i=1,BINT_SIZE do
175 | x[i] = 0
176 | end
177 | return x
178 | end
179 | local bint_zero = bint.zero
180 |
181 | --- Create a new bint with 1 value.
182 | function bint.one()
183 | local x = setmetatable({}, bint)
184 | x[1] = 1
185 | for i=2,BINT_SIZE do
186 | x[i] = 0
187 | end
188 | return x
189 | end
190 | local bint_one = bint.one
191 |
192 | -- Convert a value to a lua integer without losing precision.
193 | local function tointeger(x)
194 | x = tonumber(x)
195 | local ty = math_type(x)
196 | if ty == 'float' then
197 | local floorx = math_floor(x)
198 | if floorx == x then
199 | x = floorx
200 | ty = math_type(x)
201 | end
202 | end
203 | if ty == 'integer' then
204 | return x
205 | end
206 | end
207 |
208 | --- Create a bint from an unsigned integer.
209 | -- Treats signed integers as an unsigned integer.
210 | -- @param x A value to initialize from convertible to a lua integer.
211 | -- @return A new bint or nil in case the input cannot be represented by an integer.
212 | -- @see bint.frominteger
213 | function bint.fromuinteger(x)
214 | x = tointeger(x)
215 | if x then
216 | if x == 1 then
217 | return bint_one()
218 | elseif x == 0 then
219 | return bint_zero()
220 | end
221 | local n = setmetatable({}, bint)
222 | for i=1,BINT_SIZE do
223 | n[i] = x & BINT_WORDMAX
224 | x = x >> BINT_WORDBITS
225 | end
226 | return n
227 | end
228 | end
229 | local bint_fromuinteger = bint.fromuinteger
230 |
231 | --- Create a bint from a signed integer.
232 | -- @param x A value to initialize from convertible to a lua integer.
233 | -- @return A new bint or nil in case the input cannot be represented by an integer.
234 | -- @see bint.fromuinteger
235 | function bint.frominteger(x)
236 | x = tointeger(x)
237 | if x then
238 | if x == 1 then
239 | return bint_one()
240 | elseif x == 0 then
241 | return bint_zero()
242 | end
243 | local neg = false
244 | if x < 0 then
245 | x = math_abs(x)
246 | neg = true
247 | end
248 | local n = setmetatable({}, bint)
249 | for i=1,BINT_SIZE do
250 | n[i] = x & BINT_WORDMAX
251 | x = x >> BINT_WORDBITS
252 | end
253 | if neg then
254 | n:_unm()
255 | end
256 | return n
257 | end
258 | end
259 | local bint_frominteger = bint.frominteger
260 |
261 | local basesteps = {}
262 |
263 | -- Compute the read step for frombase function
264 | local function getbasestep(base)
265 | local step = basesteps[base]
266 | if step then
267 | return step
268 | end
269 | step = 0
270 | local dmax = 1
271 | local limit = math_maxinteger // base
272 | repeat
273 | step = step + 1
274 | dmax = dmax * base
275 | until dmax >= limit
276 | basesteps[base] = step
277 | return step
278 | end
279 |
280 | -- Compute power with lua integers.
281 | local function ipow(y, x, n)
282 | if n == 1 then
283 | return y * x
284 | elseif n & 1 == 0 then --even
285 | return ipow(y, x * x, n // 2)
286 | end
287 | return ipow(x * y, x * x, (n-1) // 2)
288 | end
289 |
290 | --- Create a bint from a string of the desired base.
291 | -- @param s The string to be converted from,
292 | -- must have only alphanumeric and '+-' characters.
293 | -- @param[opt] base Base that the number is represented, defaults to 10.
294 | -- Must be at least 2 and at most 36.
295 | -- @return A new bint or nil in case the conversion failed.
296 | function bint.frombase(s, base)
297 | if type(s) ~= 'string' then
298 | return
299 | end
300 | base = base or 10
301 | if not (base >= 2 and base <= 36) then
302 | -- number base is too large
303 | return
304 | end
305 | local step = getbasestep(base)
306 | if #s < step then
307 | -- string is small, use tonumber (faster)
308 | return bint_frominteger(tonumber(s, base))
309 | end
310 | local sign, int = s:lower():match('^([+-]?)(%w+)$')
311 | if not (sign and int) then
312 | -- invalid integer string representation
313 | return
314 | end
315 | local n = bint_zero()
316 | for i=1,#int,step do
317 | local part = int:sub(i,i+step-1)
318 | local d = tonumber(part, base)
319 | if not d then
320 | -- invalid integer string representation
321 | return
322 | end
323 | if i > 1 then
324 | n = n * ipow(1, base, #part)
325 | end
326 | if d ~= 0 then
327 | n:_add(d)
328 | end
329 | end
330 | if sign == '-' then
331 | n:_unm()
332 | end
333 | return n
334 | end
335 | local bint_frombase = bint.frombase
336 |
337 | --- Create a new bint from a string.
338 | -- The string can by a decimal number, binary number prefixed with '0b' or hexadecimal number prefixed with '0x'.
339 | -- @param s A string convertible to a bint.
340 | -- @return A new bint or nil in case the conversion failed.
341 | -- @see bint.frombase
342 | function bint.fromstring(s)
343 | if type(s) ~= 'string' then
344 | return
345 | end
346 | if s:find('^[+-]?[0-9]+$') then
347 | return bint_frombase(s, 10)
348 | elseif s:find('^[+-]?0[xX][0-9a-fA-F]+$') then
349 | return bint_frombase(s:gsub('0[xX]', '', 1), 16)
350 | elseif s:find('^[+-]?0[bB][01]+$') then
351 | return bint_frombase(s:gsub('0[bB]', '', 1), 2)
352 | end
353 | end
354 | local bint_fromstring = bint.fromstring
355 |
356 | --- Create a new bint from a buffer of little-endian bytes.
357 | -- @param buffer Buffer of bytes, extra bytes are trimmed from the right, missing bytes are padded to the right.
358 | -- @raise An assert is thrown in case buffer is not an string.
359 | -- @return A bint.
360 | function bint.fromle(buffer)
361 | assert(type(buffer) == 'string', 'buffer is not a string')
362 | if #buffer > BINT_BYTES then -- trim extra bytes from the right
363 | buffer = buffer:sub(1, BINT_BYTES)
364 | elseif #buffer < BINT_BYTES then -- add missing bytes to the right
365 | buffer = buffer..('\x00'):rep(BINT_BYTES - #buffer)
366 | end
367 | return setmetatable({BINT_LEPACKFMT:unpack(buffer)}, bint)
368 | end
369 |
370 | --- Create a new bint from a buffer of big-endian bytes.
371 | -- @param buffer Buffer of bytes, extra bytes are trimmed from the left, missing bytes are padded to the left.
372 | -- @raise An assert is thrown in case buffer is not an string.
373 | -- @return A bint.
374 | function bint.frombe(buffer)
375 | assert(type(buffer) == 'string', 'buffer is not a string')
376 | if #buffer > BINT_BYTES then -- trim extra bytes from the left
377 | buffer = buffer:sub(-BINT_BYTES, #buffer)
378 | elseif #buffer < BINT_BYTES then -- add missing bytes to the left
379 | buffer = ('\x00'):rep(BINT_BYTES - #buffer)..buffer
380 | end
381 | return setmetatable({BINT_LEPACKFMT:unpack(buffer:reverse())}, bint)
382 | end
383 |
384 | --- Create a new bint from a value.
385 | -- @param x A value convertible to a bint (string, number or another bint).
386 | -- @return A new bint, guaranteed to be a new reference in case needed.
387 | -- @raise An assert is thrown in case x is not convertible to a bint.
388 | -- @see bint.tobint
389 | -- @see bint.parse
390 | function bint.new(x)
391 | if getmetatable(x) ~= bint then
392 | local ty = type(x)
393 | if ty == 'number' then
394 | x = bint_frominteger(x)
395 | elseif ty == 'string' then
396 | x = bint_fromstring(x)
397 | end
398 | assert(x, 'value cannot be represented by a bint')
399 | return x
400 | end
401 | -- return a clone
402 | local n = setmetatable({}, bint)
403 | for i=1,BINT_SIZE do
404 | n[i] = x[i]
405 | end
406 | return n
407 | end
408 | local bint_new = bint.new
409 |
410 | --- Convert a value to a bint if possible.
411 | -- @param x A value to be converted (string, number or another bint).
412 | -- @param[opt] clone A boolean that tells if a new bint reference should be returned.
413 | -- Defaults to false.
414 | -- @return A bint or nil in case the conversion failed.
415 | -- @see bint.new
416 | -- @see bint.parse
417 | function bint.tobint(x, clone)
418 | if getmetatable(x) == bint then
419 | if not clone then
420 | return x
421 | end
422 | -- return a clone
423 | local n = setmetatable({}, bint)
424 | for i=1,BINT_SIZE do
425 | n[i] = x[i]
426 | end
427 | return n
428 | end
429 | local ty = type(x)
430 | if ty == 'number' then
431 | return bint_frominteger(x)
432 | elseif ty == 'string' then
433 | return bint_fromstring(x)
434 | end
435 | end
436 | local tobint = bint.tobint
437 |
438 | --- Convert a value to a bint if possible otherwise to a lua number.
439 | -- Useful to prepare values that you are unsure if it's going to be an integer or float.
440 | -- @param x A value to be converted (string, number or another bint).
441 | -- @param[opt] clone A boolean that tells if a new bint reference should be returned.
442 | -- Defaults to false.
443 | -- @return A bint or a lua number or nil in case the conversion failed.
444 | -- @see bint.new
445 | -- @see bint.tobint
446 | function bint.parse(x, clone)
447 | local i = tobint(x, clone)
448 | if i then
449 | return i
450 | end
451 | return tonumber(x)
452 | end
453 | local bint_parse = bint.parse
454 |
455 | --- Convert a bint to an unsigned integer.
456 | -- Note that large unsigned integers may be represented as negatives in lua integers.
457 | -- Note that lua cannot represent values larger than 64 bits,
458 | -- in that case integer values wrap around.
459 | -- @param x A bint or a number to be converted into an unsigned integer.
460 | -- @return An integer or nil in case the input cannot be represented by an integer.
461 | -- @see bint.tointeger
462 | function bint.touinteger(x)
463 | if getmetatable(x) == bint then
464 | local n = 0
465 | for i=1,BINT_SIZE do
466 | n = n | (x[i] << (BINT_WORDBITS * (i - 1)))
467 | end
468 | return n
469 | end
470 | return tointeger(x)
471 | end
472 |
473 | --- Convert a bint to a signed integer.
474 | -- It works by taking absolute values then applying the sign bit in case needed.
475 | -- Note that lua cannot represent values larger than 64 bits,
476 | -- in that case integer values wrap around.
477 | -- @param x A bint or value to be converted into an unsigned integer.
478 | -- @return An integer or nil in case the input cannot be represented by an integer.
479 | -- @see bint.touinteger
480 | function bint.tointeger(x)
481 | if getmetatable(x) == bint then
482 | local n = 0
483 | local neg = x:isneg()
484 | if neg then
485 | x = -x
486 | end
487 | for i=1,BINT_SIZE do
488 | n = n | (x[i] << (BINT_WORDBITS * (i - 1)))
489 | end
490 | if neg then
491 | n = -n
492 | end
493 | return n
494 | end
495 | return tointeger(x)
496 | end
497 | local bint_tointeger = bint.tointeger
498 |
499 | local function bint_assert_tointeger(x)
500 | x = bint_tointeger(x)
501 | if not x then
502 | error('value has no integer representation')
503 | end
504 | return x
505 | end
506 |
507 | --- Convert a bint to a lua float in case integer would wrap around or lua integer otherwise.
508 | -- Different from @{bint.tointeger} the operation does not wrap around integers,
509 | -- but digits precision are lost in the process of converting to a float.
510 | -- @param x A bint or value to be converted into a lua number.
511 | -- @return A lua number or nil in case the input cannot be represented by a number.
512 | -- @see bint.tointeger
513 | function bint.tonumber(x)
514 | if getmetatable(x) == bint then
515 | if x <= BINT_MATHMAXINTEGER and x >= BINT_MATHMININTEGER then
516 | return x:tointeger()
517 | end
518 | return tonumber(tostring(x))
519 | end
520 | return tonumber(x)
521 | end
522 | local bint_tonumber = bint.tonumber
523 |
524 | -- Compute base letters to use in bint.tobase
525 | local BASE_LETTERS = {}
526 | do
527 | for i=1,36 do
528 | BASE_LETTERS[i-1] = ('0123456789abcdefghijklmnopqrstuvwxyz'):sub(i,i)
529 | end
530 | end
531 |
532 | --- Convert a bint to a string in the desired base.
533 | -- @param x The bint to be converted from.
534 | -- @param[opt] base Base to be represented, defaults to 10.
535 | -- Must be at least 2 and at most 36.
536 | -- @param[opt] unsigned Whether to output as an unsigned integer.
537 | -- Defaults to false for base 10 and true for others.
538 | -- When unsigned is false the symbol '-' is prepended in negative values.
539 | -- @return A string representing the input.
540 | -- @raise An assert is thrown in case the base is invalid.
541 | function bint.tobase(x, base, unsigned)
542 | x = tobint(x)
543 | if not x then
544 | -- x is a fractional float or something else
545 | return
546 | end
547 | base = base or 10
548 | if not (base >= 2 and base <= 36) then
549 | -- number base is too large
550 | return
551 | end
552 | if unsigned == nil then
553 | unsigned = base ~= 10
554 | end
555 | local isxneg = x:isneg()
556 | if (base == 10 and not unsigned) or (base == 16 and unsigned and not isxneg) then
557 | if x <= BINT_MATHMAXINTEGER and x >= BINT_MATHMININTEGER then
558 | -- integer is small, use tostring or string.format (faster)
559 | local n = x:tointeger()
560 | if base == 10 then
561 | return tostring(n)
562 | elseif unsigned then
563 | return string_format('%x', n)
564 | end
565 | end
566 | end
567 | local ss = {}
568 | local neg = not unsigned and isxneg
569 | x = neg and x:abs() or bint_new(x)
570 | local xiszero = x:iszero()
571 | if xiszero then
572 | return '0'
573 | end
574 | -- calculate basepow
575 | local step = 0
576 | local basepow = 1
577 | local limit = (BINT_WORDMSB - 1) // base
578 | repeat
579 | step = step + 1
580 | basepow = basepow * base
581 | until basepow >= limit
582 | -- serialize base digits
583 | local size = BINT_SIZE
584 | local xd, carry, d
585 | repeat
586 | -- single word division
587 | carry = 0
588 | xiszero = true
589 | for i=size,1,-1 do
590 | carry = carry | x[i]
591 | d, xd = carry // basepow, carry % basepow
592 | if xiszero and d ~= 0 then
593 | size = i
594 | xiszero = false
595 | end
596 | x[i] = d
597 | carry = xd << BINT_WORDBITS
598 | end
599 | -- digit division
600 | for _=1,step do
601 | xd, d = xd // base, xd % base
602 | if xiszero and xd == 0 and d == 0 then
603 | -- stop on leading zeros
604 | break
605 | end
606 | table_insert(ss, 1, BASE_LETTERS[d])
607 | end
608 | until xiszero
609 | if neg then
610 | table_insert(ss, 1, '-')
611 | end
612 | return table_concat(ss)
613 | end
614 |
615 | local function bint_assert_convert(x)
616 | return assert(tobint(x), 'value has not integer representation')
617 | end
618 |
619 | --- Convert a bint to a buffer of little-endian bytes.
620 | -- @param x A bint or lua integer.
621 | -- @param[opt] trim If true, zero bytes on the right are trimmed.
622 | -- @return A buffer of bytes representing the input.
623 | -- @raise Asserts in case input is not convertible to an integer.
624 | function bint.tole(x, trim)
625 | x = bint_assert_convert(x)
626 | local s = BINT_LEPACKFMT:pack(table_unpack(x))
627 | if trim then
628 | s = s:gsub('\x00+$', '')
629 | if s == '' then
630 | s = '\x00'
631 | end
632 | end
633 | return s
634 | end
635 |
636 | --- Convert a bint to a buffer of big-endian bytes.
637 | -- @param x A bint or lua integer.
638 | -- @param[opt] trim If true, zero bytes on the left are trimmed.
639 | -- @return A buffer of bytes representing the input.
640 | -- @raise Asserts in case input is not convertible to an integer.
641 | function bint.tobe(x, trim)
642 | x = bint_assert_convert(x)
643 | local s = BINT_LEPACKFMT:pack(table_unpack(x)):reverse()
644 | if trim then
645 | s = s:gsub('^\x00+', '')
646 | if s == '' then
647 | s = '\x00'
648 | end
649 | end
650 | return s
651 | end
652 |
653 | --- Check if a number is 0 considering bints.
654 | -- @param x A bint or a lua number.
655 | function bint.iszero(x)
656 | if getmetatable(x) == bint then
657 | for i=1,BINT_SIZE do
658 | if x[i] ~= 0 then
659 | return false
660 | end
661 | end
662 | return true
663 | end
664 | return x == 0
665 | end
666 |
667 | --- Check if a number is 1 considering bints.
668 | -- @param x A bint or a lua number.
669 | function bint.isone(x)
670 | if getmetatable(x) == bint then
671 | if x[1] ~= 1 then
672 | return false
673 | end
674 | for i=2,BINT_SIZE do
675 | if x[i] ~= 0 then
676 | return false
677 | end
678 | end
679 | return true
680 | end
681 | return x == 1
682 | end
683 |
684 | --- Check if a number is -1 considering bints.
685 | -- @param x A bint or a lua number.
686 | function bint.isminusone(x)
687 | if getmetatable(x) == bint then
688 | for i=1,BINT_SIZE do
689 | if x[i] ~= BINT_WORDMAX then
690 | return false
691 | end
692 | end
693 | return true
694 | end
695 | return x == -1
696 | end
697 | local bint_isminusone = bint.isminusone
698 |
699 | --- Check if the input is a bint.
700 | -- @param x Any lua value.
701 | function bint.isbint(x)
702 | return getmetatable(x) == bint
703 | end
704 |
705 | --- Check if the input is a lua integer or a bint.
706 | -- @param x Any lua value.
707 | function bint.isintegral(x)
708 | return getmetatable(x) == bint or math_type(x) == 'integer'
709 | end
710 |
711 | --- Check if the input is a bint or a lua number.
712 | -- @param x Any lua value.
713 | function bint.isnumeric(x)
714 | return getmetatable(x) == bint or type(x) == 'number'
715 | end
716 |
717 | --- Get the number type of the input (bint, integer or float).
718 | -- @param x Any lua value.
719 | -- @return Returns "bint" for bints, "integer" for lua integers,
720 | -- "float" from lua floats or nil otherwise.
721 | function bint.type(x)
722 | if getmetatable(x) == bint then
723 | return 'bint'
724 | end
725 | return math_type(x)
726 | end
727 |
728 | --- Check if a number is negative considering bints.
729 | -- Zero is guaranteed to never be negative for bints.
730 | -- @param x A bint or a lua number.
731 | function bint.isneg(x)
732 | if getmetatable(x) == bint then
733 | return x[BINT_SIZE] & BINT_WORDMSB ~= 0
734 | end
735 | return x < 0
736 | end
737 | local bint_isneg = bint.isneg
738 |
739 | --- Check if a number is positive considering bints.
740 | -- @param x A bint or a lua number.
741 | function bint.ispos(x)
742 | if getmetatable(x) == bint then
743 | return not x:isneg() and not x:iszero()
744 | end
745 | return x > 0
746 | end
747 |
748 | --- Check if a number is even considering bints.
749 | -- @param x A bint or a lua number.
750 | function bint.iseven(x)
751 | if getmetatable(x) == bint then
752 | return x[1] & 1 == 0
753 | end
754 | return math_abs(x) % 2 == 0
755 | end
756 |
757 | --- Check if a number is odd considering bints.
758 | -- @param x A bint or a lua number.
759 | function bint.isodd(x)
760 | if getmetatable(x) == bint then
761 | return x[1] & 1 == 1
762 | end
763 | return math_abs(x) % 2 == 1
764 | end
765 |
766 | --- Create a new bint with the maximum possible integer value.
767 | function bint.maxinteger()
768 | local x = setmetatable({}, bint)
769 | for i=1,BINT_SIZE-1 do
770 | x[i] = BINT_WORDMAX
771 | end
772 | x[BINT_SIZE] = BINT_WORDMAX ~ BINT_WORDMSB
773 | return x
774 | end
775 |
776 | --- Create a new bint with the minimum possible integer value.
777 | function bint.mininteger()
778 | local x = setmetatable({}, bint)
779 | for i=1,BINT_SIZE-1 do
780 | x[i] = 0
781 | end
782 | x[BINT_SIZE] = BINT_WORDMSB
783 | return x
784 | end
785 |
786 | --- Bitwise left shift a bint in one bit (in-place).
787 | function bint:_shlone()
788 | local wordbitsm1 = BINT_WORDBITS - 1
789 | for i=BINT_SIZE,2,-1 do
790 | self[i] = ((self[i] << 1) | (self[i-1] >> wordbitsm1)) & BINT_WORDMAX
791 | end
792 | self[1] = (self[1] << 1) & BINT_WORDMAX
793 | return self
794 | end
795 |
796 | --- Bitwise right shift a bint in one bit (in-place).
797 | function bint:_shrone()
798 | local wordbitsm1 = BINT_WORDBITS - 1
799 | for i=1,BINT_SIZE-1 do
800 | self[i] = ((self[i] >> 1) | (self[i+1] << wordbitsm1)) & BINT_WORDMAX
801 | end
802 | self[BINT_SIZE] = self[BINT_SIZE] >> 1
803 | return self
804 | end
805 |
806 | -- Bitwise left shift words of a bint (in-place). Used only internally.
807 | function bint:_shlwords(n)
808 | for i=BINT_SIZE,n+1,-1 do
809 | self[i] = self[i - n]
810 | end
811 | for i=1,n do
812 | self[i] = 0
813 | end
814 | return self
815 | end
816 |
817 | -- Bitwise right shift words of a bint (in-place). Used only internally.
818 | function bint:_shrwords(n)
819 | if n < BINT_SIZE then
820 | for i=1,BINT_SIZE-n do
821 | self[i] = self[i + n]
822 | end
823 | for i=BINT_SIZE-n+1,BINT_SIZE do
824 | self[i] = 0
825 | end
826 | else
827 | for i=1,BINT_SIZE do
828 | self[i] = 0
829 | end
830 | end
831 | return self
832 | end
833 |
834 | --- Increment a bint by one (in-place).
835 | function bint:_inc()
836 | for i=1,BINT_SIZE do
837 | local tmp = self[i]
838 | local v = (tmp + 1) & BINT_WORDMAX
839 | self[i] = v
840 | if v > tmp then
841 | break
842 | end
843 | end
844 | return self
845 | end
846 |
847 | --- Increment a number by one considering bints.
848 | -- @param x A bint or a lua number to increment.
849 | function bint.inc(x)
850 | local ix = tobint(x, true)
851 | if ix then
852 | return ix:_inc()
853 | end
854 | return x + 1
855 | end
856 |
857 | --- Decrement a bint by one (in-place).
858 | function bint:_dec()
859 | for i=1,BINT_SIZE do
860 | local tmp = self[i]
861 | local v = (tmp - 1) & BINT_WORDMAX
862 | self[i] = v
863 | if v <= tmp then
864 | break
865 | end
866 | end
867 | return self
868 | end
869 |
870 | --- Decrement a number by one considering bints.
871 | -- @param x A bint or a lua number to decrement.
872 | function bint.dec(x)
873 | local ix = tobint(x, true)
874 | if ix then
875 | return ix:_dec()
876 | end
877 | return x - 1
878 | end
879 |
880 | --- Assign a bint to a new value (in-place).
881 | -- @param y A value to be copied from.
882 | -- @raise Asserts in case inputs are not convertible to integers.
883 | function bint:_assign(y)
884 | y = bint_assert_convert(y)
885 | for i=1,BINT_SIZE do
886 | self[i] = y[i]
887 | end
888 | return self
889 | end
890 |
891 | --- Take absolute of a bint (in-place).
892 | function bint:_abs()
893 | if self:isneg() then
894 | self:_unm()
895 | end
896 | return self
897 | end
898 |
899 | --- Take absolute of a number considering bints.
900 | -- @param x A bint or a lua number to take the absolute.
901 | function bint.abs(x)
902 | local ix = tobint(x, true)
903 | if ix then
904 | return ix:_abs()
905 | end
906 | return math_abs(x)
907 | end
908 | local bint_abs = bint.abs
909 |
910 | --- Take the floor of a number considering bints.
911 | -- @param x A bint or a lua number to perform the floor operation.
912 | function bint.floor(x)
913 | if getmetatable(x) == bint then
914 | return bint_new(x)
915 | end
916 | return bint_new(math_floor(tonumber(x)))
917 | end
918 |
919 | --- Take ceil of a number considering bints.
920 | -- @param x A bint or a lua number to perform the ceil operation.
921 | function bint.ceil(x)
922 | if getmetatable(x) == bint then
923 | return bint_new(x)
924 | end
925 | return bint_new(math_ceil(tonumber(x)))
926 | end
927 |
928 | --- Wrap around bits of an integer (discarding left bits) considering bints.
929 | -- @param x A bint or a lua integer.
930 | -- @param y Number of right bits to preserve.
931 | function bint.bwrap(x, y)
932 | x = bint_assert_convert(x)
933 | if y <= 0 then
934 | return bint_zero()
935 | elseif y < BINT_BITS then
936 | return x & (bint_one() << y):_dec()
937 | end
938 | return bint_new(x)
939 | end
940 |
941 | --- Rotate left integer x by y bits considering bints.
942 | -- @param x A bint or a lua integer.
943 | -- @param y Number of bits to rotate.
944 | function bint.brol(x, y)
945 | x, y = bint_assert_convert(x), bint_assert_tointeger(y)
946 | if y > 0 then
947 | return (x << y) | (x >> (BINT_BITS - y))
948 | elseif y < 0 then
949 | if y ~= math_mininteger then
950 | return x:bror(-y)
951 | else
952 | x:bror(-(y+1))
953 | x:bror(1)
954 | end
955 | end
956 | return x
957 | end
958 |
959 | --- Rotate right integer x by y bits considering bints.
960 | -- @param x A bint or a lua integer.
961 | -- @param y Number of bits to rotate.
962 | function bint.bror(x, y)
963 | x, y = bint_assert_convert(x), bint_assert_tointeger(y)
964 | if y > 0 then
965 | return (x >> y) | (x << (BINT_BITS - y))
966 | elseif y < 0 then
967 | if y ~= math_mininteger then
968 | return x:brol(-y)
969 | else
970 | x:brol(-(y+1))
971 | x:brol(1)
972 | end
973 | end
974 | return x
975 | end
976 |
977 | --- Truncate a number to a bint.
978 | -- Floats numbers are truncated, that is, the fractional port is discarded.
979 | -- @param x A number to truncate.
980 | -- @return A new bint or nil in case the input does not fit in a bint or is not a number.
981 | function bint.trunc(x)
982 | if getmetatable(x) ~= bint then
983 | x = tonumber(x)
984 | if x then
985 | local ty = math_type(x)
986 | if ty == 'float' then
987 | -- truncate to integer
988 | x = math_modf(x)
989 | end
990 | return bint_frominteger(x)
991 | end
992 | return
993 | end
994 | return bint_new(x)
995 | end
996 |
997 | --- Take maximum between two numbers considering bints.
998 | -- @param x A bint or lua number to compare.
999 | -- @param y A bint or lua number to compare.
1000 | -- @return A bint or a lua number. Guarantees to return a new bint for integer values.
1001 | function bint.max(x, y)
1002 | local ix, iy = tobint(x), tobint(y)
1003 | if ix and iy then
1004 | return bint_new(ix > iy and ix or iy)
1005 | end
1006 | return bint_parse(math_max(x, y))
1007 | end
1008 |
1009 | --- Take minimum between two numbers considering bints.
1010 | -- @param x A bint or lua number to compare.
1011 | -- @param y A bint or lua number to compare.
1012 | -- @return A bint or a lua number. Guarantees to return a new bint for integer values.
1013 | function bint.min(x, y)
1014 | local ix, iy = tobint(x), tobint(y)
1015 | if ix and iy then
1016 | return bint_new(ix < iy and ix or iy)
1017 | end
1018 | return bint_parse(math_min(x, y))
1019 | end
1020 |
1021 | --- Add an integer to a bint (in-place).
1022 | -- @param y An integer to be added.
1023 | -- @raise Asserts in case inputs are not convertible to integers.
1024 | function bint:_add(y)
1025 | y = bint_assert_convert(y)
1026 | local carry = 0
1027 | for i=1,BINT_SIZE do
1028 | local tmp = self[i] + y[i] + carry
1029 | carry = tmp >> BINT_WORDBITS
1030 | self[i] = tmp & BINT_WORDMAX
1031 | end
1032 | return self
1033 | end
1034 |
1035 | --- Add two numbers considering bints.
1036 | -- @param x A bint or a lua number to be added.
1037 | -- @param y A bint or a lua number to be added.
1038 | function bint.__add(x, y)
1039 | local ix, iy = tobint(x), tobint(y)
1040 | if ix and iy then
1041 | local z = setmetatable({}, bint)
1042 | local carry = 0
1043 | for i=1,BINT_SIZE do
1044 | local tmp = ix[i] + iy[i] + carry
1045 | carry = tmp >> BINT_WORDBITS
1046 | z[i] = tmp & BINT_WORDMAX
1047 | end
1048 | return z
1049 | end
1050 | return bint_tonumber(x) + bint_tonumber(y)
1051 | end
1052 |
1053 | --- Subtract an integer from a bint (in-place).
1054 | -- @param y An integer to subtract.
1055 | -- @raise Asserts in case inputs are not convertible to integers.
1056 | function bint:_sub(y)
1057 | y = bint_assert_convert(y)
1058 | local borrow = 0
1059 | local wordmaxp1 = BINT_WORDMAX + 1
1060 | for i=1,BINT_SIZE do
1061 | local res = self[i] + wordmaxp1 - y[i] - borrow
1062 | self[i] = res & BINT_WORDMAX
1063 | borrow = (res >> BINT_WORDBITS) ~ 1
1064 | end
1065 | return self
1066 | end
1067 |
1068 | --- Subtract two numbers considering bints.
1069 | -- @param x A bint or a lua number to be subtracted from.
1070 | -- @param y A bint or a lua number to subtract.
1071 | function bint.__sub(x, y)
1072 | local ix, iy = tobint(x), tobint(y)
1073 | if ix and iy then
1074 | local z = setmetatable({}, bint)
1075 | local borrow = 0
1076 | local wordmaxp1 = BINT_WORDMAX + 1
1077 | for i=1,BINT_SIZE do
1078 | local res = ix[i] + wordmaxp1 - iy[i] - borrow
1079 | z[i] = res & BINT_WORDMAX
1080 | borrow = (res >> BINT_WORDBITS) ~ 1
1081 | end
1082 | return z
1083 | end
1084 | return bint_tonumber(x) - bint_tonumber(y)
1085 | end
1086 |
1087 | --- Multiply two numbers considering bints.
1088 | -- @param x A bint or a lua number to multiply.
1089 | -- @param y A bint or a lua number to multiply.
1090 | function bint.__mul(x, y)
1091 | local ix, iy = tobint(x), tobint(y)
1092 | if ix and iy then
1093 | local z = bint_zero()
1094 | local sizep1 = BINT_SIZE+1
1095 | local s = sizep1
1096 | local e = 0
1097 | for i=1,BINT_SIZE do
1098 | if ix[i] ~= 0 or iy[i] ~= 0 then
1099 | e = math_max(e, i)
1100 | s = math_min(s, i)
1101 | end
1102 | end
1103 | for i=s,e do
1104 | for j=s,math_min(sizep1-i,e) do
1105 | local a = ix[i] * iy[j]
1106 | if a ~= 0 then
1107 | local carry = 0
1108 | for k=i+j-1,BINT_SIZE do
1109 | local tmp = z[k] + (a & BINT_WORDMAX) + carry
1110 | carry = tmp >> BINT_WORDBITS
1111 | z[k] = tmp & BINT_WORDMAX
1112 | a = a >> BINT_WORDBITS
1113 | end
1114 | end
1115 | end
1116 | end
1117 | return z
1118 | end
1119 | return bint_tonumber(x) * bint_tonumber(y)
1120 | end
1121 |
1122 | --- Check if bints are equal.
1123 | -- @param x A bint to compare.
1124 | -- @param y A bint to compare.
1125 | function bint.__eq(x, y)
1126 | for i=1,BINT_SIZE do
1127 | if x[i] ~= y[i] then
1128 | return false
1129 | end
1130 | end
1131 | return true
1132 | end
1133 |
1134 | --- Check if numbers are equal considering bints.
1135 | -- @param x A bint or lua number to compare.
1136 | -- @param y A bint or lua number to compare.
1137 | function bint.eq(x, y)
1138 | local ix, iy = tobint(x), tobint(y)
1139 | if ix and iy then
1140 | return ix == iy
1141 | end
1142 | return x == y
1143 | end
1144 | local bint_eq = bint.eq
1145 |
1146 | local function findleftbit(x)
1147 | for i=BINT_SIZE,1,-1 do
1148 | local v = x[i]
1149 | if v ~= 0 then
1150 | local j = 0
1151 | repeat
1152 | v = v >> 1
1153 | j = j + 1
1154 | until v == 0
1155 | return (i-1)*BINT_WORDBITS + j - 1, i
1156 | end
1157 | end
1158 | end
1159 |
1160 | -- Single word division modulus
1161 | local function sudivmod(nume, deno)
1162 | local rema
1163 | local carry = 0
1164 | for i=BINT_SIZE,1,-1 do
1165 | carry = carry | nume[i]
1166 | nume[i] = carry // deno
1167 | rema = carry % deno
1168 | carry = rema << BINT_WORDBITS
1169 | end
1170 | return rema
1171 | end
1172 |
1173 | --- Perform unsigned division and modulo operation between two integers considering bints.
1174 | -- This is effectively the same of @{bint.udiv} and @{bint.umod}.
1175 | -- @param x The numerator, must be a bint or a lua integer.
1176 | -- @param y The denominator, must be a bint or a lua integer.
1177 | -- @return The quotient following the remainder, both bints.
1178 | -- @raise Asserts on attempt to divide by zero
1179 | -- or if inputs are not convertible to integers.
1180 | -- @see bint.udiv
1181 | -- @see bint.umod
1182 | function bint.udivmod(x, y)
1183 | local nume = bint_new(x)
1184 | local deno = bint_assert_convert(y)
1185 | -- compute if high bits of denominator are all zeros
1186 | local ishighzero = true
1187 | for i=2,BINT_SIZE do
1188 | if deno[i] ~= 0 then
1189 | ishighzero = false
1190 | break
1191 | end
1192 | end
1193 | if ishighzero then
1194 | -- try to divide by a single word (optimization)
1195 | local low = deno[1]
1196 | assert(low ~= 0, 'attempt to divide by zero')
1197 | if low == 1 then
1198 | -- denominator is one
1199 | return nume, bint_zero()
1200 | elseif low <= (BINT_WORDMSB - 1) then
1201 | -- can do single word division
1202 | local rema = sudivmod(nume, low)
1203 | return nume, bint_fromuinteger(rema)
1204 | end
1205 | end
1206 | if nume:ult(deno) then
1207 | -- denominator is greater than numerator
1208 | return bint_zero(), nume
1209 | end
1210 | -- align leftmost digits in numerator and denominator
1211 | local denolbit = findleftbit(deno)
1212 | local numelbit, numesize = findleftbit(nume)
1213 | local bit = numelbit - denolbit
1214 | deno = deno << bit
1215 | local wordmaxp1 = BINT_WORDMAX + 1
1216 | local wordbitsm1 = BINT_WORDBITS - 1
1217 | local denosize = numesize
1218 | local quot = bint_zero()
1219 | while bit >= 0 do
1220 | -- compute denominator <= numerator
1221 | local le = true
1222 | local size = math_max(numesize, denosize)
1223 | for i=size,1,-1 do
1224 | local a, b = deno[i], nume[i]
1225 | if a ~= b then
1226 | le = a < b
1227 | break
1228 | end
1229 | end
1230 | -- if the portion of the numerator above the denominator is greater or equal than to the denominator
1231 | if le then
1232 | -- subtract denominator from the portion of the numerator
1233 | local borrow = 0
1234 | for i=1,size do
1235 | local res = nume[i] + wordmaxp1 - deno[i] - borrow
1236 | nume[i] = res & BINT_WORDMAX
1237 | borrow = (res >> BINT_WORDBITS) ~ 1
1238 | end
1239 | -- concatenate 1 to the right bit of the quotient
1240 | local i = (bit // BINT_WORDBITS) + 1
1241 | quot[i] = quot[i] | (1 << (bit % BINT_WORDBITS))
1242 | end
1243 | -- shift right the denominator in one bit
1244 | for i=1,denosize-1 do
1245 | deno[i] = ((deno[i] >> 1) | (deno[i+1] << wordbitsm1)) & BINT_WORDMAX
1246 | end
1247 | local lastdenoword = deno[denosize] >> 1
1248 | deno[denosize] = lastdenoword
1249 | -- recalculate denominator size (optimization)
1250 | if lastdenoword == 0 then
1251 | while deno[denosize] == 0 do
1252 | denosize = denosize - 1
1253 | end
1254 | if denosize == 0 then
1255 | break
1256 | end
1257 | end
1258 | -- decrement current set bit for the quotient
1259 | bit = bit - 1
1260 | end
1261 | -- the remaining numerator is the remainder
1262 | return quot, nume
1263 | end
1264 | local bint_udivmod = bint.udivmod
1265 |
1266 | --- Perform unsigned division between two integers considering bints.
1267 | -- @param x The numerator, must be a bint or a lua integer.
1268 | -- @param y The denominator, must be a bint or a lua integer.
1269 | -- @return The quotient, a bint.
1270 | -- @raise Asserts on attempt to divide by zero
1271 | -- or if inputs are not convertible to integers.
1272 | function bint.udiv(x, y)
1273 | return (bint_udivmod(x, y))
1274 | end
1275 |
1276 | --- Perform unsigned integer modulo operation between two integers considering bints.
1277 | -- @param x The numerator, must be a bint or a lua integer.
1278 | -- @param y The denominator, must be a bint or a lua integer.
1279 | -- @return The remainder, a bint.
1280 | -- @raise Asserts on attempt to divide by zero
1281 | -- or if the inputs are not convertible to integers.
1282 | function bint.umod(x, y)
1283 | local _, rema = bint_udivmod(x, y)
1284 | return rema
1285 | end
1286 | local bint_umod = bint.umod
1287 |
1288 | --- Perform integer truncate division and modulo operation between two numbers considering bints.
1289 | -- This is effectively the same of @{bint.tdiv} and @{bint.tmod}.
1290 | -- @param x The numerator, a bint or lua number.
1291 | -- @param y The denominator, a bint or lua number.
1292 | -- @return The quotient following the remainder, both bint or lua number.
1293 | -- @raise Asserts on attempt to divide by zero or on division overflow.
1294 | -- @see bint.tdiv
1295 | -- @see bint.tmod
1296 | function bint.tdivmod(x, y)
1297 | local ax, ay = bint_abs(x), bint_abs(y)
1298 | local ix, iy = tobint(ax), tobint(ay)
1299 | local quot, rema
1300 | if ix and iy then
1301 | assert(not (bint_eq(x, BINT_MININTEGER) and bint_isminusone(y)), 'division overflow')
1302 | quot, rema = bint_udivmod(ix, iy)
1303 | else
1304 | quot, rema = ax // ay, ax % ay
1305 | end
1306 | local isxneg, isyneg = bint_isneg(x), bint_isneg(y)
1307 | if isxneg ~= isyneg then
1308 | quot = -quot
1309 | end
1310 | if isxneg then
1311 | rema = -rema
1312 | end
1313 | return quot, rema
1314 | end
1315 | local bint_tdivmod = bint.tdivmod
1316 |
1317 | --- Perform truncate division between two numbers considering bints.
1318 | -- Truncate division is a division that rounds the quotient towards zero.
1319 | -- @param x The numerator, a bint or lua number.
1320 | -- @param y The denominator, a bint or lua number.
1321 | -- @return The quotient, a bint or lua number.
1322 | -- @raise Asserts on attempt to divide by zero or on division overflow.
1323 | function bint.tdiv(x, y)
1324 | return (bint_tdivmod(x, y))
1325 | end
1326 |
1327 | --- Perform integer truncate modulo operation between two numbers considering bints.
1328 | -- The operation is defined as the remainder of the truncate division
1329 | -- (division that rounds the quotient towards zero).
1330 | -- @param x The numerator, a bint or lua number.
1331 | -- @param y The denominator, a bint or lua number.
1332 | -- @return The remainder, a bint or lua number.
1333 | -- @raise Asserts on attempt to divide by zero or on division overflow.
1334 | function bint.tmod(x, y)
1335 | local _, rema = bint_tdivmod(x, y)
1336 | return rema
1337 | end
1338 |
1339 | --- Perform integer floor division and modulo operation between two numbers considering bints.
1340 | -- This is effectively the same of @{bint.__idiv} and @{bint.__mod}.
1341 | -- @param x The numerator, a bint or lua number.
1342 | -- @param y The denominator, a bint or lua number.
1343 | -- @return The quotient following the remainder, both bint or lua number.
1344 | -- @raise Asserts on attempt to divide by zero.
1345 | -- @see bint.__idiv
1346 | -- @see bint.__mod
1347 | function bint.idivmod(x, y)
1348 | local ix, iy = tobint(x), tobint(y)
1349 | if ix and iy then
1350 | local isnumeneg = ix[BINT_SIZE] & BINT_WORDMSB ~= 0
1351 | local isdenoneg = iy[BINT_SIZE] & BINT_WORDMSB ~= 0
1352 | if isnumeneg then
1353 | ix = -ix
1354 | end
1355 | if isdenoneg then
1356 | iy = -iy
1357 | end
1358 | local quot, rema = bint_udivmod(ix, iy)
1359 | if isnumeneg ~= isdenoneg then
1360 | quot:_unm()
1361 | -- round quotient towards minus infinity
1362 | if not rema:iszero() then
1363 | quot:_dec()
1364 | -- adjust the remainder
1365 | if isnumeneg and not isdenoneg then
1366 | rema:_unm():_add(y)
1367 | elseif isdenoneg and not isnumeneg then
1368 | rema:_add(y)
1369 | end
1370 | end
1371 | elseif isnumeneg then
1372 | -- adjust the remainder
1373 | rema:_unm()
1374 | end
1375 | return quot, rema
1376 | end
1377 | local nx, ny = bint_tonumber(x), bint_tonumber(y)
1378 | return nx // ny, nx % ny
1379 | end
1380 | local bint_idivmod = bint.idivmod
1381 |
1382 | --- Perform floor division between two numbers considering bints.
1383 | -- Floor division is a division that rounds the quotient towards minus infinity,
1384 | -- resulting in the floor of the division of its operands.
1385 | -- @param x The numerator, a bint or lua number.
1386 | -- @param y The denominator, a bint or lua number.
1387 | -- @return The quotient, a bint or lua number.
1388 | -- @raise Asserts on attempt to divide by zero.
1389 | function bint.__idiv(x, y)
1390 | local ix, iy = tobint(x), tobint(y)
1391 | if ix and iy then
1392 | local isnumeneg = ix[BINT_SIZE] & BINT_WORDMSB ~= 0
1393 | local isdenoneg = iy[BINT_SIZE] & BINT_WORDMSB ~= 0
1394 | if isnumeneg then
1395 | ix = -ix
1396 | end
1397 | if isdenoneg then
1398 | iy = -iy
1399 | end
1400 | local quot, rema = bint_udivmod(ix, iy)
1401 | if isnumeneg ~= isdenoneg then
1402 | quot:_unm()
1403 | -- round quotient towards minus infinity
1404 | if not rema:iszero() then
1405 | quot:_dec()
1406 | end
1407 | end
1408 | return quot, rema
1409 | end
1410 | return bint_tonumber(x) // bint_tonumber(y)
1411 | end
1412 |
1413 | --- Perform division between two numbers considering bints.
1414 | -- This always casts inputs to floats, for integer division only use @{bint.__idiv}.
1415 | -- @param x The numerator, a bint or lua number.
1416 | -- @param y The denominator, a bint or lua number.
1417 | -- @return The quotient, a lua number.
1418 | function bint.__div(x, y)
1419 | return bint_tonumber(x) / bint_tonumber(y)
1420 | end
1421 |
1422 | --- Perform integer floor modulo operation between two numbers considering bints.
1423 | -- The operation is defined as the remainder of the floor division
1424 | -- (division that rounds the quotient towards minus infinity).
1425 | -- @param x The numerator, a bint or lua number.
1426 | -- @param y The denominator, a bint or lua number.
1427 | -- @return The remainder, a bint or lua number.
1428 | -- @raise Asserts on attempt to divide by zero.
1429 | function bint.__mod(x, y)
1430 | local _, rema = bint_idivmod(x, y)
1431 | return rema
1432 | end
1433 |
1434 | --- Perform integer power between two integers considering bints.
1435 | -- If y is negative then pow is performed as an unsigned integer.
1436 | -- @param x The base, an integer.
1437 | -- @param y The exponent, an integer.
1438 | -- @return The result of the pow operation, a bint.
1439 | -- @raise Asserts in case inputs are not convertible to integers.
1440 | -- @see bint.__pow
1441 | -- @see bint.upowmod
1442 | function bint.ipow(x, y)
1443 | y = bint_assert_convert(y)
1444 | if y:iszero() then
1445 | return bint_one()
1446 | elseif y:isone() then
1447 | return bint_new(x)
1448 | end
1449 | -- compute exponentiation by squaring
1450 | x, y = bint_new(x), bint_new(y)
1451 | local z = bint_one()
1452 | repeat
1453 | if y:iseven() then
1454 | x = x * x
1455 | y:_shrone()
1456 | else
1457 | z = x * z
1458 | x = x * x
1459 | y:_dec():_shrone()
1460 | end
1461 | until y:isone()
1462 | return x * z
1463 | end
1464 |
1465 | --- Perform integer power between two unsigned integers over a modulus considering bints.
1466 | -- @param x The base, an integer.
1467 | -- @param y The exponent, an integer.
1468 | -- @param m The modulus, an integer.
1469 | -- @return The result of the pow operation, a bint.
1470 | -- @raise Asserts in case inputs are not convertible to integers.
1471 | -- @see bint.__pow
1472 | -- @see bint.ipow
1473 | function bint.upowmod(x, y, m)
1474 | m = bint_assert_convert(m)
1475 | if m:isone() then
1476 | return bint_zero()
1477 | end
1478 | x, y = bint_new(x), bint_new(y)
1479 | local z = bint_one()
1480 | x = bint_umod(x, m)
1481 | while not y:iszero() do
1482 | if y:isodd() then
1483 | z = bint_umod(z*x, m)
1484 | end
1485 | y:_shrone()
1486 | x = bint_umod(x*x, m)
1487 | end
1488 | return z
1489 | end
1490 |
1491 | --- Perform numeric power between two numbers considering bints.
1492 | -- This always casts inputs to floats, for integer power only use @{bint.ipow}.
1493 | -- @param x The base, a bint or lua number.
1494 | -- @param y The exponent, a bint or lua number.
1495 | -- @return The result of the pow operation, a lua number.
1496 | -- @see bint.ipow
1497 | function bint.__pow(x, y)
1498 | return bint_tonumber(x) ^ bint_tonumber(y)
1499 | end
1500 |
1501 | --- Bitwise left shift integers considering bints.
1502 | -- @param x An integer to perform the bitwise shift.
1503 | -- @param y An integer with the number of bits to shift.
1504 | -- @return The result of shift operation, a bint.
1505 | -- @raise Asserts in case inputs are not convertible to integers.
1506 | function bint.__shl(x, y)
1507 | x, y = bint_new(x), bint_assert_tointeger(y)
1508 | if y == math_mininteger or math_abs(y) >= BINT_BITS then
1509 | return bint_zero()
1510 | end
1511 | if y < 0 then
1512 | return x >> -y
1513 | end
1514 | local nvals = y // BINT_WORDBITS
1515 | if nvals ~= 0 then
1516 | x:_shlwords(nvals)
1517 | y = y - nvals * BINT_WORDBITS
1518 | end
1519 | if y ~= 0 then
1520 | local wordbitsmy = BINT_WORDBITS - y
1521 | for i=BINT_SIZE,2,-1 do
1522 | x[i] = ((x[i] << y) | (x[i-1] >> wordbitsmy)) & BINT_WORDMAX
1523 | end
1524 | x[1] = (x[1] << y) & BINT_WORDMAX
1525 | end
1526 | return x
1527 | end
1528 |
1529 | --- Bitwise right shift integers considering bints.
1530 | -- @param x An integer to perform the bitwise shift.
1531 | -- @param y An integer with the number of bits to shift.
1532 | -- @return The result of shift operation, a bint.
1533 | -- @raise Asserts in case inputs are not convertible to integers.
1534 | function bint.__shr(x, y)
1535 | x, y = bint_new(x), bint_assert_tointeger(y)
1536 | if y == math_mininteger or math_abs(y) >= BINT_BITS then
1537 | return bint_zero()
1538 | end
1539 | if y < 0 then
1540 | return x << -y
1541 | end
1542 | local nvals = y // BINT_WORDBITS
1543 | if nvals ~= 0 then
1544 | x:_shrwords(nvals)
1545 | y = y - nvals * BINT_WORDBITS
1546 | end
1547 | if y ~= 0 then
1548 | local wordbitsmy = BINT_WORDBITS - y
1549 | for i=1,BINT_SIZE-1 do
1550 | x[i] = ((x[i] >> y) | (x[i+1] << wordbitsmy)) & BINT_WORDMAX
1551 | end
1552 | x[BINT_SIZE] = x[BINT_SIZE] >> y
1553 | end
1554 | return x
1555 | end
1556 |
1557 | --- Bitwise AND bints (in-place).
1558 | -- @param y An integer to perform bitwise AND.
1559 | -- @raise Asserts in case inputs are not convertible to integers.
1560 | function bint:_band(y)
1561 | y = bint_assert_convert(y)
1562 | for i=1,BINT_SIZE do
1563 | self[i] = self[i] & y[i]
1564 | end
1565 | return self
1566 | end
1567 |
1568 | --- Bitwise AND two integers considering bints.
1569 | -- @param x An integer to perform bitwise AND.
1570 | -- @param y An integer to perform bitwise AND.
1571 | -- @raise Asserts in case inputs are not convertible to integers.
1572 | function bint.__band(x, y)
1573 | return bint_new(x):_band(y)
1574 | end
1575 |
1576 | --- Bitwise OR bints (in-place).
1577 | -- @param y An integer to perform bitwise OR.
1578 | -- @raise Asserts in case inputs are not convertible to integers.
1579 | function bint:_bor(y)
1580 | y = bint_assert_convert(y)
1581 | for i=1,BINT_SIZE do
1582 | self[i] = self[i] | y[i]
1583 | end
1584 | return self
1585 | end
1586 |
1587 | --- Bitwise OR two integers considering bints.
1588 | -- @param x An integer to perform bitwise OR.
1589 | -- @param y An integer to perform bitwise OR.
1590 | -- @raise Asserts in case inputs are not convertible to integers.
1591 | function bint.__bor(x, y)
1592 | return bint_new(x):_bor(y)
1593 | end
1594 |
1595 | --- Bitwise XOR bints (in-place).
1596 | -- @param y An integer to perform bitwise XOR.
1597 | -- @raise Asserts in case inputs are not convertible to integers.
1598 | function bint:_bxor(y)
1599 | y = bint_assert_convert(y)
1600 | for i=1,BINT_SIZE do
1601 | self[i] = self[i] ~ y[i]
1602 | end
1603 | return self
1604 | end
1605 |
1606 | --- Bitwise XOR two integers considering bints.
1607 | -- @param x An integer to perform bitwise XOR.
1608 | -- @param y An integer to perform bitwise XOR.
1609 | -- @raise Asserts in case inputs are not convertible to integers.
1610 | function bint.__bxor(x, y)
1611 | return bint_new(x):_bxor(y)
1612 | end
1613 |
1614 | --- Bitwise NOT a bint (in-place).
1615 | function bint:_bnot()
1616 | for i=1,BINT_SIZE do
1617 | self[i] = (~self[i]) & BINT_WORDMAX
1618 | end
1619 | return self
1620 | end
1621 |
1622 | --- Bitwise NOT a bint.
1623 | -- @param x An integer to perform bitwise NOT.
1624 | -- @raise Asserts in case inputs are not convertible to integers.
1625 | function bint.__bnot(x)
1626 | local y = setmetatable({}, bint)
1627 | for i=1,BINT_SIZE do
1628 | y[i] = (~x[i]) & BINT_WORDMAX
1629 | end
1630 | return y
1631 | end
1632 |
1633 | --- Negate a bint (in-place). This effectively applies two's complements.
1634 | function bint:_unm()
1635 | return self:_bnot():_inc()
1636 | end
1637 |
1638 | --- Negate a bint. This effectively applies two's complements.
1639 | -- @param x A bint to perform negation.
1640 | function bint.__unm(x)
1641 | return (~x):_inc()
1642 | end
1643 |
1644 | --- Compare if integer x is less than y considering bints (unsigned version).
1645 | -- @param x Left integer to compare.
1646 | -- @param y Right integer to compare.
1647 | -- @raise Asserts in case inputs are not convertible to integers.
1648 | -- @see bint.__lt
1649 | function bint.ult(x, y)
1650 | x, y = bint_assert_convert(x), bint_assert_convert(y)
1651 | for i=BINT_SIZE,1,-1 do
1652 | local a, b = x[i], y[i]
1653 | if a ~= b then
1654 | return a < b
1655 | end
1656 | end
1657 | return false
1658 | end
1659 |
1660 | --- Compare if bint x is less or equal than y considering bints (unsigned version).
1661 | -- @param x Left integer to compare.
1662 | -- @param y Right integer to compare.
1663 | -- @raise Asserts in case inputs are not convertible to integers.
1664 | -- @see bint.__le
1665 | function bint.ule(x, y)
1666 | x, y = bint_assert_convert(x), bint_assert_convert(y)
1667 | for i=BINT_SIZE,1,-1 do
1668 | local a, b = x[i], y[i]
1669 | if a ~= b then
1670 | return a < b
1671 | end
1672 | end
1673 | return true
1674 | end
1675 |
1676 | --- Compare if number x is less than y considering bints and signs.
1677 | -- @param x Left value to compare, a bint or lua number.
1678 | -- @param y Right value to compare, a bint or lua number.
1679 | -- @see bint.ult
1680 | function bint.__lt(x, y)
1681 | local ix, iy = tobint(x), tobint(y)
1682 | if ix and iy then
1683 | local xneg = ix[BINT_SIZE] & BINT_WORDMSB ~= 0
1684 | local yneg = iy[BINT_SIZE] & BINT_WORDMSB ~= 0
1685 | if xneg == yneg then
1686 | for i=BINT_SIZE,1,-1 do
1687 | local a, b = ix[i], iy[i]
1688 | if a ~= b then
1689 | return a < b
1690 | end
1691 | end
1692 | return false
1693 | end
1694 | return xneg and not yneg
1695 | end
1696 | return bint_tonumber(x) < bint_tonumber(y)
1697 | end
1698 |
1699 | --- Compare if number x is less or equal than y considering bints and signs.
1700 | -- @param x Left value to compare, a bint or lua number.
1701 | -- @param y Right value to compare, a bint or lua number.
1702 | -- @see bint.ule
1703 | function bint.__le(x, y)
1704 | local ix, iy = tobint(x), tobint(y)
1705 | if ix and iy then
1706 | local xneg = ix[BINT_SIZE] & BINT_WORDMSB ~= 0
1707 | local yneg = iy[BINT_SIZE] & BINT_WORDMSB ~= 0
1708 | if xneg == yneg then
1709 | for i=BINT_SIZE,1,-1 do
1710 | local a, b = ix[i], iy[i]
1711 | if a ~= b then
1712 | return a < b
1713 | end
1714 | end
1715 | return true
1716 | end
1717 | return xneg and not yneg
1718 | end
1719 | return bint_tonumber(x) <= bint_tonumber(y)
1720 | end
1721 |
1722 | --- Convert a bint to a string on base 10.
1723 | -- @see bint.tobase
1724 | function bint:__tostring()
1725 | return self:tobase(10)
1726 | end
1727 |
1728 | -- Allow creating bints by calling bint itself
1729 | setmetatable(bint, {
1730 | __call = function(_, x)
1731 | return bint_new(x)
1732 | end
1733 | })
1734 |
1735 | BINT_MATHMININTEGER, BINT_MATHMAXINTEGER = bint_new(math.mininteger), bint_new(math.maxinteger)
1736 | BINT_MININTEGER = bint.mininteger()
1737 | memo[memoindex] = bint
1738 |
1739 | return bint
1740 |
1741 | end
1742 |
1743 | return newmodule
1744 |
1745 | --[[
1746 | The MIT License (MIT)
1747 |
1748 | Copyright (c) 2020-2024 Eduardo Bart (https://github.com/edubart)
1749 |
1750 | Permission is hereby granted, free of charge, to any person obtaining a copy
1751 | of this software and associated documentation files (the "Software"), to deal
1752 | in the Software without restriction, including without limitation the rights
1753 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
1754 | copies of the Software, and to permit persons to whom the Software is
1755 | furnished to do so, subject to the following conditions:
1756 |
1757 | The above copyright notice and this permission notice shall be included in all
1758 | copies or substantial portions of the Software.
1759 |
1760 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1761 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1762 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1763 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1764 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
1765 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1766 | SOFTWARE.
1767 | ]]
1768 |
--------------------------------------------------------------------------------
/docs/index.html:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
Small portable arbitrary-precision integer arithmetic library in pure Lua for
53 | computing with large integers.
54 |
Different from most arbitrary-precision integer libraries in pure Lua out there this one
55 | uses an array of lua integers as underlying data-type in its implementation instead of
56 | using strings or large tables, this make it efficient for working with fixed width integers
57 | and to make bitwise operations.
58 |
59 |
Design goals
60 |
61 |
The main design goal of this library is to be small, correct, self contained and use few
62 | resources while retaining acceptable performance and feature completeness.
63 |
64 |
The library is designed to follow recent Lua integer semantics, this means that
65 | integer overflow warps around,
66 | signed integers are implemented using two-complement arithmetic rules,
67 | integer division operations rounds towards minus infinity,
68 | any mixed operations with float numbers promotes the value to a float,
69 | and the usual division/power operation always promotes to floats.
70 |
71 |
The library is designed to be possible to work with only unsigned integer arithmetic
72 | when using the proper methods.
73 |
74 |
All the lua arithmetic operators (+, -, *, //, /, %) and bitwise operators (&, |, ~, <<, >>)
75 | are implemented as metamethods.
76 |
77 |
The integer size must be fixed in advance and the library is designed to be more efficient when
78 | working with integers of sizes between 64-4096 bits. If you need to work with really huge numbers
79 | without size restrictions then use another library. This choice has been made to have more efficiency
80 | in that specific size range.
81 |
82 |
Usage
83 |
84 |
First on you should require the bint file including how many bits the bint module will work with,
85 | by calling the returned function from the require, for example:
86 |
87 |
88 |
89 | local bint = require'bint'(1024)
90 |
91 |
92 |
93 |
For more information about its arguments see newmodule.
94 | Then when you need create a bint, you can use one of the following functions:
95 |
96 |
97 |
bint.fromuinteger (convert from lua integers, but read as unsigned integer)
98 |
bint.frominteger (convert from lua integers, preserving the sign)
99 |
bint.frombase (convert from arbitrary bases, like hexadecimal)
100 |
bint.fromstring (convert from arbitrary string, support binary/hexadecimal/decimal)
101 |
bint.trunc (convert from lua numbers, truncating the fractional part)
102 |
bint.new (convert from anything, asserts on invalid integers)
103 |
bint.tobint (convert from anything, returns nil on invalid integers)
104 |
bint.parse (convert from anything, returns a lua number as fallback)
You can also call bint as it is an alias to bint.new.
111 | In doubt use bint.new to create a new bint.
112 |
113 |
Then you can use all the usual lua numeric operations on it,
114 | all the arithmetic metamethods are implemented.
115 | When you are done computing and need to get the result,
116 | get the output from one of the following functions:
117 |
118 |
119 |
bint.touinteger (convert to a lua integer, wraps around as an unsigned integer)
120 |
bint.tointeger (convert to a lua integer, wraps around, preserves the sign)
121 |
bint.tonumber (convert to lua float, losing precision)
To output a very large integer with no loss you probably want to use bint.tobase
127 | or call tostring to get a string representation.
128 |
129 |
Precautions
130 |
131 |
All library functions can be mixed with lua numbers,
132 | this makes easy to mix operations between bints and lua numbers,
133 | however the user should take care in some situations:
134 |
135 |
136 |
Don't mix integers and float operations if you want to work with integers only.
137 |
Don't use the regular equal operator ('==') to compare values from this library,
138 | unless you know in advance that both values are of the same primitive type,
139 | otherwise it will always return false, use bint.eq to be safe.
140 |
Don't pass fractional numbers to functions that an integer is expected
141 |
Don't mix operations between bint classes with different sizes as this is not supported, this
142 | will throw assertions.
143 |
Remember that casting back to lua integers or numbers precision can be lost.
144 |
For dividing while preserving integers use the bint.__idiv (the '//' operator).
145 |
For doing power operation preserving integers use the bint.ipow function.
146 |
Configure the proper integer size you intend to work with, otherwise large integers may wrap around.
517 | Create a new bint module representing integers of the desired bit size.
518 | This is the returned function when require 'bint' is called.
519 |
520 |
521 |
Parameters:
522 |
523 |
bits
524 | Number of bits for the integer representation, must be multiple of wordbits and
525 | at least 64.
526 |
527 |
wordbits
528 | Number of the bits for the internal word,
529 | defaults to half of Lua's integer size.
530 | (optional)
531 |
532 |
533 |
534 |
535 |
536 |
537 |
538 |
539 |
540 |
541 | zero ()
542 |
543 |
544 | Create a new bint with 0 value.
545 |
546 |
547 |
548 |
549 |
550 |
551 |
552 |
553 |
554 |
555 | one ()
556 |
557 |
558 | Create a new bint with 1 value.
559 |
560 |
561 |
562 |
563 |
564 |
565 |
566 |
567 |
568 |
569 | fromuinteger (x)
570 |
571 |
572 | Create a bint from an unsigned integer.
573 | Treats signed integers as an unsigned integer.
574 |
575 |
576 |
Parameters:
577 |
578 |
x
579 | A value to initialize from convertible to a lua integer.
580 |
581 |
582 |
583 |
Returns:
584 |
585 |
586 | A new bint or nil in case the input cannot be represented by an integer.
587 |
588 |
589 |
590 |
631 | Create a bint from a string of the desired base.
632 |
633 |
634 |
Parameters:
635 |
636 |
s
637 | The string to be converted from,
638 | must have only alphanumeric and '+-' characters.
639 |
640 |
base
641 | Base that the number is represented, defaults to 10.
642 | Must be at least 2 and at most 36.
643 | (optional)
644 |
645 |
646 |
647 |
Returns:
648 |
649 |
650 | A new bint or nil in case the conversion failed.
651 |
652 |
653 |
654 |
655 |
656 |
657 |
658 |
659 | fromstring (s)
660 |
661 |
662 | Create a new bint from a string.
663 | The string can by a decimal number, binary number prefixed with '0b' or hexadecimal number prefixed with '0x'.
664 |
665 |
666 |
Parameters:
667 |
668 |
s
669 | A string convertible to a bint.
670 |
671 |
672 |
673 |
Returns:
674 |
675 |
676 | A new bint or nil in case the conversion failed.
677 |
678 |
679 |
680 |
813 | Convert a value to a bint if possible otherwise to a lua number.
814 | Useful to prepare values that you are unsure if it's going to be an integer or float.
815 |
816 |
817 |
Parameters:
818 |
819 |
x
820 | A value to be converted (string, number or another bint).
821 |
822 |
clone
823 | A boolean that tells if a new bint reference should be returned.
824 | Defaults to false.
825 | (optional)
826 |
827 |
828 |
829 |
Returns:
830 |
831 |
832 | A bint or a lua number or nil in case the conversion failed.
833 |
834 |
835 |
836 |
849 | Convert a bint to an unsigned integer.
850 | Note that large unsigned integers may be represented as negatives in lua integers.
851 | Note that lua cannot represent values larger than 64 bits,
852 | in that case integer values wrap around.
853 |
854 |
855 |
Parameters:
856 |
857 |
x
858 | A bint or a number to be converted into an unsigned integer.
859 |
860 |
861 |
862 |
Returns:
863 |
864 |
865 | An integer or nil in case the input cannot be represented by an integer.
866 |
867 |
868 |
869 |
881 | Convert a bint to a signed integer.
882 | It works by taking absolute values then applying the sign bit in case needed.
883 | Note that lua cannot represent values larger than 64 bits,
884 | in that case integer values wrap around.
885 |
886 |
887 |
Parameters:
888 |
889 |
x
890 | A bint or value to be converted into an unsigned integer.
891 |
892 |
893 |
894 |
Returns:
895 |
896 |
897 | An integer or nil in case the input cannot be represented by an integer.
898 |
899 |
900 |
901 |
913 | Convert a bint to a lua float in case integer would wrap around or lua integer otherwise.
914 | Different from bint.tointeger the operation does not wrap around integers,
915 | but digits precision are lost in the process of converting to a float.
916 |
917 |
918 |
Parameters:
919 |
920 |
x
921 | A bint or value to be converted into a lua number.
922 |
923 |
924 |
925 |
Returns:
926 |
927 |
928 | A lua number or nil in case the input cannot be represented by a number.
929 |
930 |
931 |
932 |
944 | Convert a bint to a string in the desired base.
945 |
946 |
947 |
Parameters:
948 |
949 |
x
950 | The bint to be converted from.
951 |
952 |
base
953 | Base to be represented, defaults to 10.
954 | Must be at least 2 and at most 36.
955 | (optional)
956 |
957 |
unsigned
958 | Whether to output as an unsigned integer.
959 | Defaults to false for base 10 and true for others.
960 | When unsigned is false the symbol '-' is prepended in negative values.
961 | (optional)
962 |
963 |
964 |
965 |
Returns:
966 |
967 |
968 | A string representing the input.
969 |
970 |
971 |
Raises:
972 | An assert is thrown in case the base is invalid.
973 |
974 |
975 |
976 |
977 |
978 |
979 | tole (x[, trim])
980 |
981 |
982 | Convert a bint to a buffer of little-endian bytes.
983 |
984 |
985 |
Parameters:
986 |
987 |
x
988 | A bint or lua integer.
989 |
990 |
trim
991 | If true, zero bytes on the right are trimmed.
992 | (optional)
993 |
994 |
995 |
996 |
Returns:
997 |
998 |
999 | A buffer of bytes representing the input.
1000 |
1001 |
1002 |
Raises:
1003 | Asserts in case input is not convertible to an integer.
1004 |
1005 |
1006 |
1007 |
1008 |
1009 |
1010 | tobe (x[, trim])
1011 |
1012 |
1013 | Convert a bint to a buffer of big-endian bytes.
1014 |
1015 |
1016 |
Parameters:
1017 |
1018 |
x
1019 | A bint or lua integer.
1020 |
1021 |
trim
1022 | If true, zero bytes on the left are trimmed.
1023 | (optional)
1024 |
1025 |
1026 |
1027 |
Returns:
1028 |
1029 |
1030 | A buffer of bytes representing the input.
1031 |
1032 |
1033 |
Raises:
1034 | Asserts in case input is not convertible to an integer.
1035 |
1036 |
1037 |
1038 |
1039 |
1040 |
1041 | iszero (x)
1042 |
1043 |
1044 | Check if a number is 0 considering bints.
1045 |
1046 |
1047 |
Parameters:
1048 |
1049 |
x
1050 | A bint or a lua number.
1051 |
1052 |
1053 |
1054 |
1055 |
1056 |
1057 |
1058 |
1059 |
1060 |
1061 | isone (x)
1062 |
1063 |
1064 | Check if a number is 1 considering bints.
1065 |
1066 |
1067 |
Parameters:
1068 |
1069 |
x
1070 | A bint or a lua number.
1071 |
1072 |
1073 |
1074 |
1075 |
1076 |
1077 |
1078 |
1079 |
1080 |
1081 | isminusone (x)
1082 |
1083 |
1084 | Check if a number is -1 considering bints.
1085 |
1086 |
1087 |
Parameters:
1088 |
1089 |
x
1090 | A bint or a lua number.
1091 |
1092 |
1093 |
1094 |
1095 |
1096 |
1097 |
1098 |
1099 |
1100 |
1101 | isbint (x)
1102 |
1103 |
1104 | Check if the input is a bint.
1105 |
1106 |
1107 |
Parameters:
1108 |
1109 |
x
1110 | Any lua value.
1111 |
1112 |
1113 |
1114 |
1115 |
1116 |
1117 |
1118 |
1119 |
1120 |
1121 | isintegral (x)
1122 |
1123 |
1124 | Check if the input is a lua integer or a bint.
1125 |
1126 |
1127 |
Parameters:
1128 |
1129 |
x
1130 | Any lua value.
1131 |
1132 |
1133 |
1134 |
1135 |
1136 |
1137 |
1138 |
1139 |
1140 |
1141 | isnumeric (x)
1142 |
1143 |
1144 | Check if the input is a bint or a lua number.
1145 |
1146 |
1147 |
Parameters:
1148 |
1149 |
x
1150 | Any lua value.
1151 |
1152 |
1153 |
1154 |
1155 |
1156 |
1157 |
1158 |
1159 |
1160 |
1161 | type (x)
1162 |
1163 |
1164 | Get the number type of the input (bint, integer or float).
1165 |
1166 |
1167 |
Parameters:
1168 |
1169 |
x
1170 | Any lua value.
1171 |
1172 |
1173 |
1174 |
Returns:
1175 |
1176 |
1177 | Returns "bint" for bints, "integer" for lua integers,
1178 | "float" from lua floats or nil otherwise.
1179 |
1180 |
1181 |
1182 |
1183 |
1184 |
1185 |
1186 |
1187 | isneg (x)
1188 |
1189 |
1190 | Check if a number is negative considering bints.
1191 | Zero is guaranteed to never be negative for bints.
1192 |
1193 |
1194 |
Parameters:
1195 |
1196 |
x
1197 | A bint or a lua number.
1198 |
1199 |
1200 |
1201 |
1202 |
1203 |
1204 |
1205 |
1206 |
1207 |
1208 | ispos (x)
1209 |
1210 |
1211 | Check if a number is positive considering bints.
1212 |
1213 |
1214 |
Parameters:
1215 |
1216 |
x
1217 | A bint or a lua number.
1218 |
1219 |
1220 |
1221 |
1222 |
1223 |
1224 |
1225 |
1226 |
1227 |
1228 | iseven (x)
1229 |
1230 |
1231 | Check if a number is even considering bints.
1232 |
1233 |
1234 |
Parameters:
1235 |
1236 |
x
1237 | A bint or a lua number.
1238 |
1239 |
1240 |
1241 |
1242 |
1243 |
1244 |
1245 |
1246 |
1247 |
1248 | isodd (x)
1249 |
1250 |
1251 | Check if a number is odd considering bints.
1252 |
1253 |
1254 |
Parameters:
1255 |
1256 |
x
1257 | A bint or a lua number.
1258 |
1259 |
1260 |
1261 |
1262 |
1263 |
1264 |
1265 |
1266 |
1267 |
1268 | maxinteger ()
1269 |
1270 |
1271 | Create a new bint with the maximum possible integer value.
1272 |
1273 |
1274 |
1275 |
1276 |
1277 |
1278 |
1279 |
1280 |
1281 |
1282 | mininteger ()
1283 |
1284 |
1285 | Create a new bint with the minimum possible integer value.
1286 |
1287 |
1288 |
1289 |
1290 |
1291 |
1292 |
1293 |
1294 |
1295 |
1296 | _shlone ()
1297 |
1298 |
1299 | Bitwise left shift a bint in one bit (in-place).
1300 |
1301 |
1302 |
1303 |
1304 |
1305 |
1306 |
1307 |
1308 |
1309 |
1310 | _shrone ()
1311 |
1312 |
1313 | Bitwise right shift a bint in one bit (in-place).
1314 |
1315 |
1316 |
1317 |
1318 |
1319 |
1320 |
1321 |
1322 |
1323 |
1324 | _inc ()
1325 |
1326 |
1327 | Increment a bint by one (in-place).
1328 |
1329 |
1330 |
1331 |
1332 |
1333 |
1334 |
1335 |
1336 |
1337 |
1338 | inc (x)
1339 |
1340 |
1341 | Increment a number by one considering bints.
1342 |
1343 |
1344 |
Parameters:
1345 |
1346 |
x
1347 | A bint or a lua number to increment.
1348 |
1349 |
1350 |
1351 |
1352 |
1353 |
1354 |
1355 |
1356 |
1357 |
1358 | _dec ()
1359 |
1360 |
1361 | Decrement a bint by one (in-place).
1362 |
1363 |
1364 |
1365 |
1366 |
1367 |
1368 |
1369 |
1370 |
1371 |
1372 | dec (x)
1373 |
1374 |
1375 | Decrement a number by one considering bints.
1376 |
1377 |
1378 |
Parameters:
1379 |
1380 |
x
1381 | A bint or a lua number to decrement.
1382 |
1383 |
1384 |
1385 |
1386 |
1387 |
1388 |
1389 |
1390 |
1391 |
1392 | _assign (y)
1393 |
1394 |
1395 | Assign a bint to a new value (in-place).
1396 |
1397 |
1398 |
Parameters:
1399 |
1400 |
y
1401 | A value to be copied from.
1402 |
1403 |
1404 |
1405 |
1406 |
Raises:
1407 | Asserts in case inputs are not convertible to integers.
1408 |
1409 |
1410 |
1411 |
1412 |
1413 |
1414 | _abs ()
1415 |
1416 |
1417 | Take absolute of a bint (in-place).
1418 |
1419 |
1420 |
1421 |
1422 |
1423 |
1424 |
1425 |
1426 |
1427 |
1428 | abs (x)
1429 |
1430 |
1431 | Take absolute of a number considering bints.
1432 |
1433 |
1434 |
Parameters:
1435 |
1436 |
x
1437 | A bint or a lua number to take the absolute.
1438 |
1439 |
1440 |
1441 |
1442 |
1443 |
1444 |
1445 |
1446 |
1447 |
1448 | floor (x)
1449 |
1450 |
1451 | Take the floor of a number considering bints.
1452 |
1453 |
1454 |
Parameters:
1455 |
1456 |
x
1457 | A bint or a lua number to perform the floor operation.
1458 |
1459 |
1460 |
1461 |
1462 |
1463 |
1464 |
1465 |
1466 |
1467 |
1468 | ceil (x)
1469 |
1470 |
1471 | Take ceil of a number considering bints.
1472 |
1473 |
1474 |
Parameters:
1475 |
1476 |
x
1477 | A bint or a lua number to perform the ceil operation.
1478 |
1479 |
1480 |
1481 |
1482 |
1483 |
1484 |
1485 |
1486 |
1487 |
1488 | bwrap (x, y)
1489 |
1490 |
1491 | Wrap around bits of an integer (discarding left bits) considering bints.
1492 |
1493 |
1494 |
Parameters:
1495 |
1496 |
x
1497 | A bint or a lua integer.
1498 |
1499 |
y
1500 | Number of right bits to preserve.
1501 |
1502 |
1503 |
1504 |
1505 |
1506 |
1507 |
1508 |
1509 |
1510 |
1511 | brol (x, y)
1512 |
1513 |
1514 | Rotate left integer x by y bits considering bints.
1515 |
1516 |
1517 |
Parameters:
1518 |
1519 |
x
1520 | A bint or a lua integer.
1521 |
1522 |
y
1523 | Number of bits to rotate.
1524 |
1525 |
1526 |
1527 |
1528 |
1529 |
1530 |
1531 |
1532 |
1533 |
1534 | bror (x, y)
1535 |
1536 |
1537 | Rotate right integer x by y bits considering bints.
1538 |
1539 |
1540 |
Parameters:
1541 |
1542 |
x
1543 | A bint or a lua integer.
1544 |
1545 |
y
1546 | Number of bits to rotate.
1547 |
1548 |
1549 |
1550 |
1551 |
1552 |
1553 |
1554 |
1555 |
1556 |
1557 | trunc (x)
1558 |
1559 |
1560 | Truncate a number to a bint.
1561 | Floats numbers are truncated, that is, the fractional port is discarded.
1562 |
1563 |
1564 |
Parameters:
1565 |
1566 |
x
1567 | A number to truncate.
1568 |
1569 |
1570 |
1571 |
Returns:
1572 |
1573 |
1574 | A new bint or nil in case the input does not fit in a bint or is not a number.
1575 |
1576 |
1577 |
1578 |
1579 |
1580 |
1581 |
1582 |
1583 | max (x, y)
1584 |
1585 |
1586 | Take maximum between two numbers considering bints.
1587 |
1588 |
1589 |
Parameters:
1590 |
1591 |
x
1592 | A bint or lua number to compare.
1593 |
1594 |
y
1595 | A bint or lua number to compare.
1596 |
1597 |
1598 |
1599 |
Returns:
1600 |
1601 |
1602 | A bint or a lua number. Guarantees to return a new bint for integer values.
1603 |
1604 |
1605 |
1606 |
1607 |
1608 |
1609 |
1610 |
1611 | min (x, y)
1612 |
1613 |
1614 | Take minimum between two numbers considering bints.
1615 |
1616 |
1617 |
Parameters:
1618 |
1619 |
x
1620 | A bint or lua number to compare.
1621 |
1622 |
y
1623 | A bint or lua number to compare.
1624 |
1625 |
1626 |
1627 |
Returns:
1628 |
1629 |
1630 | A bint or a lua number. Guarantees to return a new bint for integer values.
1631 |
1632 |
1633 |
1634 |
1635 |
1636 |
1637 |
1638 |
1639 | _add (y)
1640 |
1641 |
1642 | Add an integer to a bint (in-place).
1643 |
1644 |
1645 |
Parameters:
1646 |
1647 |
y
1648 | An integer to be added.
1649 |
1650 |
1651 |
1652 |
1653 |
Raises:
1654 | Asserts in case inputs are not convertible to integers.
1655 |
1656 |
1657 |
1658 |
x
1738 | A bint or a lua number to multiply.
1739 |
1740 |
y
1741 | A bint or a lua number to multiply.
1742 |
1743 |
1744 |
1745 |
1746 |
1747 |
1748 |
1749 |
1750 |
1751 |
1752 | __eq (x, y)
1753 |
1754 |
1755 | Check if bints are equal.
1756 |
1757 |
1758 |
Parameters:
1759 |
1760 |
x
1761 | A bint to compare.
1762 |
1763 |
y
1764 | A bint to compare.
1765 |
1766 |
1767 |
1768 |
1769 |
1770 |
1771 |
1772 |
1773 |
1774 |
1775 | eq (x, y)
1776 |
1777 |
1778 | Check if numbers are equal considering bints.
1779 |
1780 |
1781 |
Parameters:
1782 |
1783 |
x
1784 | A bint or lua number to compare.
1785 |
1786 |
y
1787 | A bint or lua number to compare.
1788 |
1789 |
1790 |
1791 |
1792 |
1793 |
1794 |
1795 |
1796 |
1797 |
1798 | udivmod (x, y)
1799 |
1800 |
1801 | Perform unsigned division and modulo operation between two integers considering bints.
1802 | This is effectively the same of bint.udiv and bint.umod.
1803 |
1804 |
1805 |
Parameters:
1806 |
1807 |
x
1808 | The numerator, must be a bint or a lua integer.
1809 |
1810 |
y
1811 | The denominator, must be a bint or a lua integer.
1812 |
1813 |
1814 |
1815 |
Returns:
1816 |
1817 |
1818 | The quotient following the remainder, both bints.
1819 |
1820 |
1821 |
Raises:
1822 | Asserts on attempt to divide by zero
1823 | or if inputs are not convertible to integers.
1824 |
1825 |
1838 | Perform unsigned division between two integers considering bints.
1839 |
1840 |
1841 |
Parameters:
1842 |
1843 |
x
1844 | The numerator, must be a bint or a lua integer.
1845 |
1846 |
y
1847 | The denominator, must be a bint or a lua integer.
1848 |
1849 |
1850 |
1851 |
Returns:
1852 |
1853 |
1854 | The quotient, a bint.
1855 |
1856 |
1857 |
Raises:
1858 | Asserts on attempt to divide by zero
1859 | or if inputs are not convertible to integers.
1860 |
1861 |
1862 |
1863 |
1864 |
1865 |
1866 | umod (x, y)
1867 |
1868 |
1869 | Perform unsigned integer modulo operation between two integers considering bints.
1870 |
1871 |
1872 |
Parameters:
1873 |
1874 |
x
1875 | The numerator, must be a bint or a lua integer.
1876 |
1877 |
y
1878 | The denominator, must be a bint or a lua integer.
1879 |
1880 |
1881 |
1882 |
Returns:
1883 |
1884 |
1885 | The remainder, a bint.
1886 |
1887 |
1888 |
Raises:
1889 | Asserts on attempt to divide by zero
1890 | or if the inputs are not convertible to integers.
1891 |
1892 |
1893 |
1894 |
1895 |
1896 |
1897 | tdivmod (x, y)
1898 |
1899 |
1900 | Perform integer truncate division and modulo operation between two numbers considering bints.
1901 | This is effectively the same of bint.tdiv and bint.tmod.
1902 |
1903 |
1904 |
Parameters:
1905 |
1906 |
x
1907 | The numerator, a bint or lua number.
1908 |
1909 |
y
1910 | The denominator, a bint or lua number.
1911 |
1912 |
1913 |
1914 |
Returns:
1915 |
1916 |
1917 | The quotient following the remainder, both bint or lua number.
1918 |
1919 |
1920 |
Raises:
1921 | Asserts on attempt to divide by zero or on division overflow.
1922 |
1923 |
1936 | Perform truncate division between two numbers considering bints.
1937 | Truncate division is a division that rounds the quotient towards zero.
1938 |
1939 |
1940 |
Parameters:
1941 |
1942 |
x
1943 | The numerator, a bint or lua number.
1944 |
1945 |
y
1946 | The denominator, a bint or lua number.
1947 |
1948 |
1949 |
1950 |
Returns:
1951 |
1952 |
1953 | The quotient, a bint or lua number.
1954 |
1955 |
1956 |
Raises:
1957 | Asserts on attempt to divide by zero or on division overflow.
1958 |
1959 |
1960 |
1961 |
1962 |
1963 |
1964 | tmod (x, y)
1965 |
1966 |
1967 | Perform integer truncate modulo operation between two numbers considering bints.
1968 | The operation is defined as the remainder of the truncate division
1969 | (division that rounds the quotient towards zero).
1970 |
1971 |
1972 |
Parameters:
1973 |
1974 |
x
1975 | The numerator, a bint or lua number.
1976 |
1977 |
y
1978 | The denominator, a bint or lua number.
1979 |
1980 |
1981 |
1982 |
Returns:
1983 |
1984 |
1985 | The remainder, a bint or lua number.
1986 |
1987 |
1988 |
Raises:
1989 | Asserts on attempt to divide by zero or on division overflow.
1990 |
1991 |
1992 |
1993 |
1994 |
1995 |
1996 | idivmod (x, y)
1997 |
1998 |
1999 | Perform integer floor division and modulo operation between two numbers considering bints.
2000 | This is effectively the same of bint.__idiv and bint.__mod.
2001 |
2002 |
2003 |
Parameters:
2004 |
2005 |
x
2006 | The numerator, a bint or lua number.
2007 |
2008 |
y
2009 | The denominator, a bint or lua number.
2010 |
2011 |
2012 |
2013 |
Returns:
2014 |
2015 |
2016 | The quotient following the remainder, both bint or lua number.
2017 |
2018 |
2019 |
Raises:
2020 | Asserts on attempt to divide by zero.
2021 |
2022 |
2035 | Perform floor division between two numbers considering bints.
2036 | Floor division is a division that rounds the quotient towards minus infinity,
2037 | resulting in the floor of the division of its operands.
2038 |
2039 |
2040 |
Parameters:
2041 |
2042 |
x
2043 | The numerator, a bint or lua number.
2044 |
2045 |
y
2046 | The denominator, a bint or lua number.
2047 |
2048 |
2049 |
2050 |
Returns:
2051 |
2052 |
2053 | The quotient, a bint or lua number.
2054 |
2055 |
2056 |
Raises:
2057 | Asserts on attempt to divide by zero.
2058 |
2059 |
2060 |
2061 |
2062 |
2063 |
2064 | __div (x, y)
2065 |
2066 |
2067 | Perform division between two numbers considering bints.
2068 | This always casts inputs to floats, for integer division only use bint.__idiv.
2069 |
2070 |
2071 |
Parameters:
2072 |
2073 |
x
2074 | The numerator, a bint or lua number.
2075 |
2076 |
y
2077 | The denominator, a bint or lua number.
2078 |
2096 | Perform integer floor modulo operation between two numbers considering bints.
2097 | The operation is defined as the remainder of the floor division
2098 | (division that rounds the quotient towards minus infinity).
2099 |
2100 |
2101 |
Parameters:
2102 |
2103 |
x
2104 | The numerator, a bint or lua number.
2105 |
2106 |
y
2107 | The denominator, a bint or lua number.
2108 |
2109 |
2110 |
2111 |
Returns:
2112 |
2113 |
2114 | The remainder, a bint or lua number.
2115 |
2116 |
2117 |
Raises:
2118 | Asserts on attempt to divide by zero.
2119 |
2120 |
2121 |
2122 |
2123 |
2124 |
2125 | ipow (x, y)
2126 |
2127 |
2128 | Perform integer power between two integers considering bints.
2129 | If y is negative then pow is performed as an unsigned integer.
2130 |
2131 |
2132 |
Parameters:
2133 |
2134 |
x
2135 | The base, an integer.
2136 |
2137 |
y
2138 | The exponent, an integer.
2139 |
2140 |
2141 |
2142 |
Returns:
2143 |
2144 |
2145 | The result of the pow operation, a bint.
2146 |
2147 |
2148 |
Raises:
2149 | Asserts in case inputs are not convertible to integers.
2150 |
2151 |
2202 | Perform numeric power between two numbers considering bints.
2203 | This always casts inputs to floats, for integer power only use bint.ipow.
2204 |
2205 |
2206 |
Parameters:
2207 |
2208 |
x
2209 | The base, a bint or lua number.
2210 |
2211 |
y
2212 | The exponent, a bint or lua number.
2213 |
2214 |
2215 |
2216 |
Returns:
2217 |
2218 |
2219 | The result of the pow operation, a lua number.
2220 |
2221 |
2222 |
2223 |