lua实现大数运算

来源:互联网 发布:淘宝联盟的导购推广位 编辑:程序博客网 时间:2024/04/28 01:44

lua实现的大数运算,代码超短,目前只实现的加减乘运算


--------------------------------------------------name:bigInt--create:2015-4-1--author:闲云--blog:blog.csdn.net/xianyun2009--QQ: 836663997--QQ group:362337463------------------------------------------------local mod = 10000function show(a)print(get(a))endfunction get(a)s = {a[#a]}for i=#a-1, 1, -1 dotable.insert(s, string.format("%04d", a[i]))endreturn table.concat(s, "")endfunction create(s)if s["xyBitInt"] == true then return s endn, t, a = math.floor(#s/4), 1, {}a["xyBitInt"] = trueif #s%4 ~= 0 then a[n + 1], t = tonumber(string.sub(s, 1, #s%4), 10), #s%4 + 1 endfor i = n, 1, -1 do a[i], t= tonumber(string.sub(s, t, t + 3), 10), t + 4 endreturn aendfunction add(a, b)a, b, c, t = create(a), create(b), create("0"), 0for i = 1, math.max(#a,#b) dot = t + (a[i] or 0) + (b[i] or 0)c[i], t = t%mod, math.floor(t/mod)endwhile t ~= 0 do c[#c + 1], t = t%mod, math.floor(t/mod) endreturn cendfunction sub(a, b)a, b, c, t = create(a), create(b), create("0"), 0for i = 1, #a doc[i] = a[i] - t - (b[i] or 0)if c[i] < 0 then t, c[i] = 1, c[i] + mod  else t = 0 endendreturn cendfunction by(a, b)a, b, c, t = create(a), create(b), create("0"), 0for i = 1, #a dofor j = 1, #b dot = t + (c[i + j - 1] or 0) + a[i] * b[j]c[i + j - 1], t = t%mod, math.floor(t / mod)endif t ~= 0 then c[i + #b], t = t + (c[i + #b] or 0), 0 endendreturn cend


把以上代码保存到文件  bigInt.lua

示例: 

新建文件 example.lua 内容如下:

require("bigInt")show(add("987654321", "123456789"))show(sub("987654321", "123456789"))show(by("987654321", "123456789"))

以后用到的地方就可以直接这样简单的调用

0 0
原创粉丝点击