|
| 1 | +''' |
| 2 | + karatsuba multiplication (integer-wise) |
| 3 | + to multiply two n-digit integers, the following formula holds: |
| 4 | + => (a * c * 10^n) + (b * d) + {[(b * c) + (a * d)] * 10^(n/2)} |
| 5 | + where: a = first half of first integer |
| 6 | + b = second half of first integer |
| 7 | + c = first half of second integer |
| 8 | + d = second half of second integer |
| 9 | + this can further be used with recursion to implement divide-and-conquer |
| 10 | + wherein each product (ac, bd, bc, ad) can be calculated using the same. |
| 11 | +
|
| 12 | + note: assuming n = even & n1 = n2 |
| 13 | +''' |
| 14 | +def k_multiply(x, y): |
| 15 | + if len(x) > 1 and len(y) > 1: # base condition: length of integers > 1 |
| 16 | + a, b = x[:len(x) // 2], x[len(x) // 2:] # divide first int for a, b, |
| 17 | + c, d = y[:len(y) // 2], y[len(y) // 2:] # divide second int for c, d |
| 18 | + |
| 19 | + print(a, b, c, d) |
| 20 | + ac = k_multiply(a, c) |
| 21 | + bd = k_multiply(b, d) |
| 22 | + bc = k_multiply(b, c) |
| 23 | + ad = k_multiply(a, d) |
| 24 | + n = len(x) |
| 25 | + n2 = n // 2 |
| 26 | + prod = (ac * pow(10, n)) + (bd) + ((bc + ad) * pow(10, n2)) # prod by karatsuba |
| 27 | + |
| 28 | + return prod |
| 29 | + else: |
| 30 | + return (x[0] * y[0]) # return product if length <= 1 |
| 31 | + |
| 32 | +if __name__ == '__main__': |
| 33 | + try: |
| 34 | + first_integer = [int(x) for x in input('first integer: ')] |
| 35 | + second_integer = [int(x) for x in input('second integer: ')] |
| 36 | + |
| 37 | + if (len(second_integer) != len(first_integer)): |
| 38 | + raise ValueError |
| 39 | + |
| 40 | + prod = k_multiply(first_integer, second_integer) |
| 41 | + print(prod) |
| 42 | + except ValueError: |
| 43 | + print('Invalid Inputs') |
| 44 | + |
0 commit comments