Pull `bigint.lua` from `bigint.lua` repo

pull/37/head
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
1 changed files with 14 additions and 15 deletions

View File

@ -2,11 +2,12 @@
-- 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
-- errors and bugs earlier.
local strict = false
local strict = true
--------------------------------------------------------------------------------
local bigint = {}
setmetatable(bigint, {__call = function(_, arg) return bigint.new(arg) end})
local mt = {
__add = function(lhs, rhs)
@ -76,7 +77,7 @@ function bigint.new(num)
end
end
return self
return bigint.strip(self)
end
-- Check the type of a big
@ -96,6 +97,14 @@ function bigint.check(big, force)
return true
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
-- value)
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
while (#result.digits > 1) and (result.digits[1] == 0) do
table.remove(result.digits, 1)
end
return result
return bigint.strip(result)
end
-- FRONTEND: Addition and subtraction operations, accounting for signs
@ -460,7 +464,7 @@ end
function bigint.exponentiate(big, power)
-- Type checking for big done by bigint.multiply
assert(bigint.compare(power, bigint.new(0), ">="),
" negative powers are not supported")
"negative powers are not supported")
local exp = power:clone()
if (bigint.compare(exp, bigint.new(0), "==")) then
@ -530,12 +534,7 @@ function bigint.divide_raw(big1, big2)
end
end
-- Remove leading zeros from result
while (result.digits[1] == 0) do
table.remove(result.digits, 1)
end
return result, dividend
return bigint.strip(result), dividend
end
end