Pull bigint.lua from bigint.lua repo

This commit is contained in:
Ishaan Bhardwaj 2021-09-20 16:09:02 -04:00 committed by GitHub
parent 42375cb2b8
commit b2d0838f90
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -2,11 +2,12 @@
-- If this variable is true, then strict type checking is performed for all -- If this variable is true, then strict type checking is performed for all
-- operations. This may result in slower code, but it will allow you to catch -- operations. This may result in slower code, but it will allow you to catch
-- errors and bugs earlier. -- errors and bugs earlier.
local strict = false local strict = true
-------------------------------------------------------------------------------- --------------------------------------------------------------------------------
local bigint = {} local bigint = {}
setmetatable(bigint, {__call = function(_, arg) return bigint.new(arg) end})
local mt = { local mt = {
__add = function(lhs, rhs) __add = function(lhs, rhs)
@ -76,7 +77,7 @@ function bigint.new(num)
end end
end end
return self return bigint.strip(self)
end end
-- Check the type of a big -- Check the type of a big
@ -96,6 +97,14 @@ function bigint.check(big, force)
return true return true
end end
-- Strip leading zeroes from a big, but don't remove the last zero
function bigint.strip(big)
while (#big.digits > 1) and (big.digits[1] == 0) do
table.remove(big.digits, 1)
end
return big
end
-- Return a new big with the same digits but with a positive sign (absolute -- Return a new big with the same digits but with a positive sign (absolute
-- value) -- value)
function bigint.abs(big) function bigint.abs(big)
@ -329,12 +338,7 @@ function bigint.subtract_raw(big1, big2)
---------------------------------------------------------------------------- ----------------------------------------------------------------------------
-- Strip leading zeroes if any, but not if 0 is the only digit return bigint.strip(result)
while (#result.digits > 1) and (result.digits[1] == 0) do
table.remove(result.digits, 1)
end
return result
end end
-- FRONTEND: Addition and subtraction operations, accounting for signs -- FRONTEND: Addition and subtraction operations, accounting for signs
@ -530,12 +534,7 @@ function bigint.divide_raw(big1, big2)
end end
end end
-- Remove leading zeros from result return bigint.strip(result), dividend
while (result.digits[1] == 0) do
table.remove(result.digits, 1)
end
return result, dividend
end end
end end