Rectangular multiplication
unknown
python
2 years ago
1.2 kB
9
Indexable
def rectangle_multiplication(num1, num2):
# Convert the numbers to strings to make manipulation easier
num1_str = str(num1)
num2_str = str(num2)
# Determine the lengths of the two numbers
len1 = len(num1_str)
len2 = len(num2_str)
# Create a result array to store intermediate products
result = [0] * (len1 + len2)
# Iterate through the digits of num1 in reverse order
for i in range(len1 - 1, -1, -1):
carry = 0
d1 = int(num1_str[i])
# Iterate through the digits of num2 in reverse order
for j in range(len2 - 1, -1, -1):
d2 = int(num2_str[j])
# Calculate the product of the current digits and add to the result
temp_sum = d1 * d2 + carry + result[i + j + 1]
carry = temp_sum // 10
result[i + j + 1] = temp_sum % 10
# Add any remaining carry to the appropriate position in the result
result[i + j] += carry
# Convert the result back to an integer
result_str = ''.join(map(str, result))
result_int = int(result_str)
return result_int
# Example usage:
num1 = 123456789
num2 = 987654321
result = rectangle_multiplication(num1, num2)
print(result) # Output: 121932631112635269
Editor is loading...