How to implement Karatsuba multiplication such that it can handle odd numbers and non-equal lengths of X and Y?

233 Views Asked by At

I tried two methods. The first was to pad X and Y with 0s so they both become of even and equal length, for example:

X = 123 , Y = 45678

becomes:

X = 000123 , Y = 045678

a = 0 , b = 123 , c = 45 , d = 678

but the problem with this implementation is when inputting:

X = 100 and Y = 14

becomes:

X = 0100 , Y = 0014

a = 1 , b = 0 , c = 0 , d = 14

ac = 0

bd = 0

ad + bc = 14

then: 10^4*(0) + 10^2*(14) + 0

notice how 10^2(14) is exactly the problem we started with, this will cause infinite recursion

the second solution I tried was to pad 0s to the right side instead, and then divide the final answer by 10^(# of 0s added) but that also causes infinite recursion in some scenarios.

What should I do?

0

There are 0 best solutions below