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"))

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

  • 相关阅读:
    常用cmd命令总结
    百度地图api的简单应用(二):轻量级路径规划
    百度地图api的简单应用(一):POI检索
    R语言-八皇后问题
    8086基本IO口的仿真
    输入输出与中断
    汇编语言例子
    变量标号
    变量声明
    串操作指令2
  • 原文地址:https://www.cnblogs.com/blfbuaa/p/6918471.html
Copyright © 2011-2022 走看看