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
- lua实现大数运算
- 大数乘法运算实现
- Java实现大数运算
- 高精度大数运算的实现
- 大数运算实现(C++)
- Java实现大数加法运算
- 大数运算实现加减乘除四则运算
- C#实现大数乘法运算!!!!
- 用Lua实现位运算
- c语言版大数计算器(实现大数的加减乘除运算)
- 大数运算,队列实现大数 加法、乘法、除法、模除
- 单链表实现大数加法、大数减法、大数乘法、大数指数运算
- 汇编编写程序实现大数运算
- 大数运算(C++类实现)
- 大数运算之加法乘法---JAVA实现
- c++单链表实现大数的求和运算
- 大数运算-加法(C/C++实现)
- 大数运算-减法(C/C++实现)
- [Leetcode] 86. Partition List
- Reverse Words in a String ---leetcode 我的java题解
- Sublime Text3打造U盘便携Lua IDE
- UIAlertView点击确定后,如何跳转到storyboard中创建的另一个UIViewController?
- 黑马程序员-JAVASE入门(GUI类)
- lua实现大数运算
- 画线算法 - Bresenham原理及Java实现
- [Leetcode] 87. Scramble String
- [Leetcode] 88. Merge Sorted Array
- LeetCode - Longest Substring Without Repeating Characters
- 黑马程序员-JAVASE入门(多线程)
- 黑马程序员-JAVASE入门(集合)
- [Leetcode] 89. Gray Code
- 黑马程序员-JAVASE入门(枚举)