Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
def multiply_(num1, num2):
lines = []
len1 = len(num1)
len2 = len(num2)
for indice2 in range(0, len2):
line = ""
transfer = 0
for indice1 in range(0, len1):
digit1 = int(num1[len1-indice1-1])
digit2 = int(num2[len2-indice2-1])
single_result = digit1 * digit2 + transfer
transfer = int(single_result / 10)
new_digit = str(single_result % 10)
line += new_digit
if transfer != 0:
line += str(transfer)
lines.append(line[::-1] + "0" * indice2)
result = ""
for line in lines:
result = add_(result, line)
return result
def add_(num1, num2):
if num1 == "" and num2 == "":
return 0
elif num1 == "":
return num2
elif num2 == "":
return num1
result = ""
transfer = 0
max_len = max(len(num1), len(num2))
for indice in range(max_len):
indice1 = len(num1) - indice - 1
indice2 = len(num2) - indice - 1
digit1 = int(num1[indice1]) if indice1 >= 0 else 0
digit2 = int(num2[indice2]) if indice2 >= 0 else 0
single_result = digit1 + digit2 + transfer
transfer = int(single_result / 10)
new_digit = str(single_result % 10)
result += new_digit
if transfer != 0:
result += str(transfer)
return result[::-1]
def test_add():
n1 = 987
n2 = 1234
print(
"Actual", add_(str(n1), str(n2)),
"Expected", str(n1 + n2),
add_(str(n1), str(n2)) == str(n1 + n2)
)
def test_multiply():
n1 = 9877878
n2 = 1234
print(
"Actual", multiply_(str(n1), str(n2)),
"Expected", str(n1 * n2),
multiply_(str(n1), str(n2)) == str(n1 * n2)
)
if __name__ == '__main__':
print(multiply_("3141592653589793238462643383279502884197169399375105820974944592",
"2718281828459045235360287471352662497757247093699959574966967627"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.