zoukankan      html  css  js  c++  java
  • 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"))

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

  • 相关阅读:
    职场之道
    AlphaBlend
    感动前行——给医学媳妇写的演讲稿(非IT类)
    高等数学积分公式大全
    分析Model2系统心得
    【软考】(六)关系代数
    飞鸽传书官方站点 创立黑马程序猿训练营
    实现简单的二级级联
    const和readonly差别
    Chord算法(原理)
  • 原文地址:https://www.cnblogs.com/blfbuaa/p/6918471.html
Copyright © 2011-2022 走看看