Optimized bigint exponentiation (again)

pull/16/head
Ishaan Bhardwaj 2021-02-10 11:38:10 -05:00 committed by GitHub
parent 4920e5de1c
commit 32c2274bef
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 9 additions and 5 deletions

View File

@ -147,11 +147,11 @@ function bigint.unserialize(big, output_type, precision)
-- num is the first (precision + 1) digits, the first being separated by -- num is the first (precision + 1) digits, the first being separated by
-- a decimal point from the others -- a decimal point from the others
num = num .. big.digits[1] num = num .. math.floor(big.digits[1])
if (precision > 1) then if (precision > 1) then
num = num .. "." num = num .. "."
for i = 1, (precision - 1) do for i = 1, (precision - 1) do
num = num .. big.digits[i + 1] num = num .. math.floor(big.digits[i + 1])
end end
end end
@ -451,14 +451,18 @@ function bigint.exponentiate(big, power)
local result = bigint.new(1) local result = bigint.new(1)
local base = big:clone() local base = big:clone()
while (bigint.compare(exp, bigint.new(0), ">")) do while (true) do
if (bigint.compare( if (bigint.compare(
bigint.modulus(exp, bigint.new(2)), bigint.new(1), "==" bigint.modulus(exp, bigint.new(2)), bigint.new(1), "=="
)) then )) then
result = bigint.multiply(result, base) result = bigint.multiply(result, base)
end end
exp = bigint.divide(exp, bigint.new(2)) if (bigint.compare(exp, bigint.new(1), "==")) then
base = bigint.multiply(base, base) break
else
exp = bigint.divide(exp, bigint.new(2))
base = bigint.multiply(base, base)
end
end end
return result return result