码迷,mamicode.com
首页 > 其他好文 > 详细

lua实现大数运算

时间:2015-04-01 07:05:35      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:lua   function   大数   加减乘   

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

local mod = 10000

function add(a, b)
	t, c = 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)
	t, c = 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)
	c = {}
	for i = 1, #a do
		t = 0
		for j = 1, #b do
			t = t + (c[i + j - 1] or 0) + a[i] * (b[j] or 0)
			c[i + j - 1], t = t%mod, math.floor(t / mod)
		end
		if t ~= 0 then c[i + #b] = t + (c[i + #b] or 0) end
	end
	return c
end
function show(a)
	io.write(a[#a])
	for i = #a - 1, 1, -1 do io.write(string.format("%04d", a[i])) end
	io.write("\n")
end
function input(s)
	n, t, a = math.floor(#s/4), 1, {}
	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

a, b = input("1434444234"), input("12")
show(sub(a,b))
show(add(a,b))
show(by(a,b))


lua实现大数运算

标签:lua   function   大数   加减乘   

原文地址:http://blog.csdn.net/xianyun2009/article/details/44796823

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!