首先,我知道Python从一开始就可以处理大量数字。但是我需要自己上课与他们一起工作。我意识到添加和 sub ,并且不完全了解如何实现 mul 和 div ?
如何实现类方法 mul 和 div 以使用长算法?
这是我的代码:
class Calc:
def __init__(self, num):
self.num = num
self._data_len = len(num)
def __len__(self):
return self._data_len
def __getitem__(self, index):
return self.num[index]
def __str__(self):
return self.num
def __add__(self, num2):
self.num = self.num[::-1]
num2 = num2[::-1]
shift = 0
result = ''
maxlen = max(len(self.num), len(num2))
for i in range(maxlen):
if i < len(self.num):
a1 = int(self.num[i])
else:
a1 = 0
if i < len(num2):
b1 = int(num2[i])
else:
b1 = 0
r = a1 + b1 + shift
shift = r // 10
r = r % 10
result += str(r)
if shift > 0:
result += str(shift)
return result[::-1]
def __sub__(self, num2):
if len(self.num) & len(num2) < 10:
return int(self.num) - int(num2)
else:
char = ''
shift = 0
result = ''
if len(self.num) < len(num2):
self.num, num2 = num2, self.num
char = '-'
self.num = self.num[::-1]
num2 = num2[::-1]
maxlen = max(len(self.num), len(num2))
for i in range(maxlen):
if i < len(self.num):
a1 = int(self.num[i])
else:
a1 = 0
if i < len(num2):
b1 = int(num2[i])
else:
b1 = 0
r = a1 - b1 - shift
if r >= 0:
result += str(r)
shift = 0
else:
r += 10
shift = 1
result += str(r)
if char == '-':
result += char
return result[::-1]
示例:
a = '15321321321392130912301293120931'
b = '130382138921839219838129398123891938189'
a1 = Calc(a)
a2 = Calc(b)
a3 = a1 + a2
>>>>130382154243160541230260310425185059120
a = '15321321321392130912301293120931'
b = '130382138921839219838129398123891938189'
a1 = Calc(a)
a2 = Calc(b)
a3 = a1 - a2
>>>>-130382123600517898445998485822598817258
a = '15321321321392130912301293120931'
b = '130382138921839219838129398123891938189'
a1 = Calc(a)
a2 = Calc(b)
a3 = a1 * a2
>>>> mul??
有什么建议吗?