lua實現大數字的四則運算

2021-10-01 18:35:51 字數 2081 閱讀 8043

在使用redis的過程中,用到了lua指令碼;其中在進行long型數字的計算的時候,總是無法獲取到精確的計算值;因此根據使用情況通過字串的相關處理實現了大數字的四則運算。

local stepnum = 10000

local function build(str)

local n, c, s = math.floor(#str / 4), {}, 1

if #str % 4 ~= 0 then

c[n + 1], s = tonumber(string.sub(str, 1, #str % 4)), #str % 4 + 1

endfor i = n, 1, -1 do

c[i], s = tonumber(string.sub(str, s, s + 3)), s + 4

endreturn c

endlocal function get(c)

local r = ""

for i = #c, 1, -1 do

if tonumber(c[#c]) < 0 and tonumber(c[i]) > 0 then

local v = math.pow(10, #c[i]) - tonumber(c[i])

r = string.sub(r, 1, #r - 1) .. tostring(tonumber(string.sub(r, #r)) - 1) .. tostring(v)

else

if r ~= '' or tonumber(c[i]) ~= 0 then

r = r .. c[i]

endend

endreturn r ~= '' and r or '0'

endlocal function add(a, b)

local c, d = {}, 0

a, b = build(a), build(b)

local count = math.max(#a, #b)

for i = 1, count, 1 do

local t = d + (a[i] or 0) + (b[i] or 0)

c[i], d = tostring(t), 0

if i ~= count then

c[i], d = tostring(t % stepnum), math.floor(t/ stepnum)

endend

return get(c)

endlocal function sub(a, b)

local c, d = {}, 0

a, b = build(a), build(b)

local count = math.max(#a, #b)

for i = 1, count, 1 do

local t = d + (a[i] or 0) - (b[i] or 0)

d = 0

if i ~= count and t < 0 then

t, d = t + stepnum, -1

endc[i] = tostring(t)

endreturn get(c)

endlocal function multi(a, b)

endlocal function div(a, b)

endlocal c = add("1234567891234567890", "1234000000000000220")

print(c)

print(add('1200', '130000000'))

print(add('1200', '1300'))

print(sub('1200', '1300'))

print(sub('1300', '1200'))

print(sub('123456789', '123456789'))

print(sub('123456789', '1234567890123'))

print(sub('1234567890123', '123456789'))

歡迎指正錯誤,如果有更好的實現方法,歡迎與我分享~

最新**,參見:github**位址

大數四則運算

include include includeusing namespace std define m 1000000000000000 大數加法 將數字以字串的形式傳入add加法函式,在函式內部完成字串 陣列的轉換,然後在陣列中逐位進行相加,再判斷該位相加後是否需要進製,為了方便計算,我們將數字的...

大數的四則運算

演算法與思路 大數的加,減,乘演算法比較簡單,模擬列豎式的計算過程就好 除法模擬實現比較困難,採用減法的形式實現,例如對於大數a b,如果a b,則直接輸出商為0,否則,將a的最後strlen b 位重複減去b,直到得數小於b,將執行減法的次數賦給商的個位,然後將b的最後添上乙個0,相當於乘以10 ...

大數的四則運算

1.加法 輸入採用字元陣列儲存,然後將輸入存在整形陣列裡,然後逐位相加即可,同時注意進製處理。cpp view plain copy include include intmain b 555 c 555 scanf s m len m strlen m for i 0 i len m 1 i a ...