lua实现大数运算

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


------------------------------------------------
--name:		bigInt
--create:	2015-4-1
--author:	闲云
--blog:		blog.csdn.net/xianyun2009
--QQ: 		836663997
--QQ group:	362337463
------------------------------------------------
local mod = 10000

function show(a)
	print(get(a))
end
function get(a)
	s = {a[#a]}
	for i=#a-1, 1, -1 do
		table.insert(s, string.format("%04d", a[i]))
	end
	return table.concat(s, "")
end
function create(s)
	if s["xyBitInt"] == true then return s end
	n, t, a = math.floor(#s/4), 1, {}
	a["xyBitInt"] = true
	if #s%4 ~= 0 then a[n + 1], t = tonumber(string.sub(s, 1, #s%4), 10), #s%4 + 1 end
	for i = n, 1, -1 do a[i], t= tonumber(string.sub(s, t, t + 3), 10), t + 4 end
	return a
end
function add(a, b)
	a, b, c, t = create(a), create(b), create("0"), 0
	for i = 1, math.max(#a,#b) do
		t = t + (a[i] or 0) + (b[i] or 0)
		c[i], t = t%mod, math.floor(t/mod)
	end
	while t ~= 0 do c[#c + 1], t = t%mod, math.floor(t/mod) end
	return c
end
function sub(a, b)
	a, b, c, t = create(a), create(b), create("0"), 0
	for i = 1, #a do
		c[i] = a[i] - t - (b[i] or 0)
		if c[i] < 0 then t, c[i] = 1, c[i] + mod  else t = 0 end
	end
	return c
end
function by(a, b)
	a, b, c, t = create(a), create(b), create("0"), 0
	for i = 1, #a do
		for j = 1, #b do
			t = t + (c[i + j - 1] or 0) + a[i] * b[j]
			c[i + j - 1], t = t%mod, math.floor(t / mod)
		end
		if t ~= 0 then c[i + #b], t = t + (c[i + #b] or 0), 0 end
	end
	return c
end


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

示例: 

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

require("bigInt")

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值