Pure Lua library for working with big integers
Go to file
2020-05-16 18:42:37 +04:30
.gitignore initial commit: import bigint 2020-05-13 15:37:40 +04:30
bigint_test.lua add one more test 2020-05-16 05:23:32 +04:30
bigint.lua constructor accepts thousands separator in string 2020-05-16 18:41:42 +04:30
README.md update README 2020-05-16 18:42:37 +04:30

BigIntLua

Pure Lua library for working with big integers

Usage

BigInt = require 'bigint'

-- constructor accepts a number
a1 = BigInt(562949953421312)

-- or a string
a2 = BigInt'562949953421312'

-- or a string with thousands separator of ',' or whitespace
a3 = BigInt'562,949,953,421,312'
a4 = BigInt'562 949 953 421 312'
a1 == a2            --> true
a1 == a3            --> true
a3 == a4            --> true


-- you can compare them
a = BigInt'8,796,093,022,208'
b = BigInt'562,949,953,421,312'
c = BigInt'39,614,081,257,132,168,796,771,975,168'
a == a1             --> true
a <= a1             --> true
a == b              --> false
a <= b              --> true
c > a               --> true

-- NOTE: equality test works only with two BigInts
a = BigInt'562949953421312'
a == 562949953421312    --> false

-- NOTE: other comparisons between Lua Numbers and BigInts are ok
a = BigInt'56294995342'
a <= 56294995342    --> true
a > 12323           --> true
a >= 56294995342    --> true
32423412312 < a     --> true
32423412312 > a     --> false

-- four arithmetic operations
a = BigInt'1,099,511,627,776'           -- 2 ^ 40
b = BigInt'1,125,899,906,842,624'       -- 2 ^ 50
a + b               --> 1126999418470400
a - b               --> -1124800395214848
a * b               --> 1237940039285380274899124224
a / b               --> 0
b / a               --> 1024

-- negation
a = BigInt'562949953421312'
b = -a              --> -562949953421312
a + b               --> 0

-- divmod
a = BigInt'1,099,511,627,776'           -- 2 ^ 40
b = BigInt'1,125,899,906,842,625'       -- 2 ^ 50 + 1
b:divmod(b, a)      --> 1024, 1

-- power
a = BigInt(2)
a ^ 95              --> 39614081257132168796771975168

TODO

  • Optional thousands separator in tostring() function.
  • GCD and LCD
  • Base conversion
  • Prime check
  • Prime factorization

See also