Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python script to compute big-digit values.
#! /usr/local/bin/python3.6
"""
Computation of big-digit values
"""
import sys
import traceback
class CalcBigDigits:
N = 5
def __init__(self):
# a, b: for addition, subtraction
# c, d: for multiplication, division
self.a = [56789012,34567890,12345678,90123456,78901234]
self.b = [12345678,90123456,78901234,56789012,34567890]
self.c = [ 12,34567890,12345678,90123456,78901234]
self.d = 99
def compute(self):
""" Computation of big-digit values """
try:
self.__long_add() # long + long
self.__long_sub() # long - long
self.__long_mul() # long * short
self.__long_div() # long / short
except Exception as e:
raise
def __long_add(self):
""" Computation of long + long """
try:
z = [0 for _ in range(self.N)]
carry = 0
for i in reversed(range(self.N)):
z[i] = self.a[i] + self.b[i] + carry
if z[i] < 100000000:
carry = 0
else:
z[i] = z[i] - 100000000
carry = 1
print(" ", end="")
self.__display_l(self.a)
print("+", end="")
self.__display_l(self.b)
print("=", end="")
self.__display_l(z)
print()
except Exception as e:
raise
def __long_sub(self):
""" Computation of long - long """
try:
z = [0 for _ in range(self.N)]
borrow = 0
for i in reversed(range(self.N)):
z[i] = self.a[i] - self.b[i] - borrow
if z[i] >= 0:
borrow = 0
else:
z[i] += 100000000
borrow = 1
print(" ", end="")
self.__display_l(self.a)
print("-", end="")
self.__display_l(self.b)
print("=", end="")
self.__display_l(z)
print()
except Exception as e:
raise
def __long_mul(self):
""" Computation of long * short """
try:
z = [0 for _ in range(self.N)]
carry = 0
for i in reversed(range(self.N)):
w = self.c[i]
z[i] = (w * self.d + carry) % 100000000
carry = int((w * self.d + carry) / 100000000)
print(" ", end="")
self.__display_l(self.c)
print("*", end="")
self.__display_s(self.d)
print("=", end="")
self.__display_l(z)
print()
except Exception as e:
raise
def __long_div(self):
""" Computation of long / short """
try:
z = [0 for _ in range(self.N)]
remainder = 0
for i in range(self.N):
w = self.c[i]
z[i] = int((w + remainder) / self.d)
remainder = ((w + remainder) % self.d) * 100000000
print(" ", end="")
self.__display_l(self.c)
print("/", end="")
self.__display_s(self.d)
print("=", end="")
self.__display_l(z)
print()
except Exception as e:
raise
def __display_l(self, s):
""" Display for a long value
:param int s
"""
try:
for i in range(self.N):
print(" {:08d}".format(s[i]), end="")
print()
except Exception as e:
raise
def __display_s(self, s):
""" Display for a short value
:param int s
"""
try:
for _ in range(self.N - 1):
print(" " * 9, end="")
print(" {:08d}".format(s))
except Exception as e:
raise
if __name__ == '__main__':
try:
obj = CalcBigDigits()
obj.compute()
except Exception as e:
traceback.print_exc()
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment