众所周知,计算机中int用32位表示,可表示范围0 - 2^32,约42亿, long用64位表示,可表示范围为0-2^64 约184亿亿。如果运算是超出这个范围,就会溢出,即无法获取正确的计算结果。这时候就需要一种特殊的计算程序。本文通过Python语言,实现了一个简单的大数计算程序:通过输入两个任意长度的由数字组成的字符串,进行+ - * /计算,计算结果也是一个字符串。
1.代码
实现原理很简单,就是把我们平时笔算的过程写成了程序。由于输入是字符串,计算过程完全是笔算的逻辑,所以可支持任意长度的数据进行运算。2.代码
代码如下:
bigdata_calc.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
import sys
def get_10(c):
return ord(c)-ord('0')
def add_one_bit(n1,n2,n3=0):
a = get_10(n1)
b = get_10(n2)
sum = a+b+n3
yu = sum%10
shang = (sum-yu)/10
return str(yu),shang
def add(n1,n2):
l1=len(n1)
l2=len(n2)
s1 = n1
s2 = n2
if l1>l2:
s1 = n2
s2 = n1
l1 = len(s1)
l2 = len(s2)
sum = []
shang = 0
for i in range(l1):
c,shang = add_one_bit(s1[l1-1-i],s2[l2-1-i],shang)
sum.append(c)
for i in range(l1,l2):
c,shang = add_one_bit('0',s2[l2-1-i],shang)
sum.append(c)
if shang > 0:
sum.append(str(shang))
for i in range(len(sum)/2):
tmp = sum[i]
sum[i]=sum[len(sum)-1-i]
sum[len(sum)-1-i] = tmp
return sum
def mul(n1,n2):
l = len(n1)
sum=[]
for i in range(l):
v = get_10(n1[i])
if v>0:
sum_tmp = n2
for j in range(l-1-i):
sum_tmp += "0"
add_v = sum_tmp
for j in range(1,v):
sum_tmp = add(sum_tmp,add_v)
if i==0:
sum = sum_tmp
else:
sum = add(sum,sum_tmp)
return sum
def sub_one_bit(n1,n2,n3):
a = get_10(n1)
b = get_10(n2)
sub = a-b-n3
jie=0
while sub<0:
jie += 1
sub += 10
return str(sub),jie
def large(n1,n2):
if len(n1)>len(n2):
return True
elif len(n1)<len(n2):
return False
else:
for i in range(len(n1)):
if ord(n1[i])>=ord(n2[i]):
return True
return False
def sub(n1,n2):
s1 = n1
s2 = n2
flag=False
if not large(n1,n2):
s1 = n2
s2 = n1
flag = True
l1 = len(s1)
l2 = len(s2)
sub = []
jie = 0
for i in range(l2):
c,jie = sub_one_bit(s1[l1-1-i],s2[l2-1-i],jie)
sub.append(c)
has_jie = 0
if jie>0:
c,jie = sub_one_bit(n1[l2-1-l1],str(jie),0)
sub.append(c)
has_jie=1
while has_jie<l1-l2:
sub.append(s1[l1-l2-1-has_jie])
has_jie += 1
if flag:
sub.append('-')
for i in range(len(sub)/2):
tmp = sub[i]
sub[i]=sub[len(sub)-1-i]
sub[len(sub)-1-i] = tmp
return sub
def div(n1,n2):
return "Todo..."
def calc(n1,op,n2):
if op == '+':
return add(n1,n2)
elif op == '-':
return sub(n1,n2)
elif op == '*':
return mul(n1,n2)
elif op == '/':
return div(n1,n2)
else:
return "unsupported operation"
if __name__ == '__main__':
if len(sys.argv)<4:
print "Usage: bigdata_calc.py num1 {+,-,*,/} num2"
else:
res = calc(sys.argv[1],sys.argv[2],sys.argv[3])
print "%50s\n%s\n%50s\n=\n%50s" %(sys.argv[1],sys.argv[2],sys.argv[3],"".join(res))
说明:仅为个人娱乐性编写, 程序目前仅支持正数据的加 、减 、乘运算,除法还未实现。
虽然个人进行了测试,但难免还有bug,请指正。
3.测试
测试一:
123
*
456
=
56088
测试二:
123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789
*
123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789
=
15241578780673678546105778311537878076969977842402077607834177373266277138698376
90413047663907941887364731910821521934278311957735101981191892004648682028105472
0515622620750190521
结果如下: