Karatsuba Algorithm for fast Multiplication of Large Decimal Numbers represented as Strings
Given two numeric strings A and B, the task is to find the product of the two numeric strings efficiently.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: A = 5678, B = 1234
Input: A = 74638463789, B = 35284567382
Approach: The given problem can be solved using Karastuba’s Algorithm for Fast Multiplication, the idea is to append zeroes in front of the integers such that both the integers have an equal and even number of digits n. Thereafter, divide the numbers in the following way:
A = Al * 10n/2 + Ar [Al and Ar contain leftmost and rightmost n/2 digits of A]
B = Bl * 10n/2 + Br [Bl and Br contain leftmost and rightmost n/2 digits of B]
- Therefore, the product A * B can also be represented as follows:
A * B = (Al * 10n/2 + Ar) * (Bl * 10n/2 + Br)
=> A * B = 10n*Al*Bl + 10n/2*(Al*Br + Bl*Ar) + Ar*Br
=> A * B = 10n*Al*Bl + 10n/2*((Al + Ar)*(Bl + Br) – Al*Bl – Ar*Br) + Ar*Br [since Al*Br + Bl*Ar = (Al + Ar)*(Bl + Br) – Al*Bl – Ar*Br]
Notice that the above expression only requires three multiplications Al*Bl, Ar*Br, and (Al + Ar)*(Bl + Br), instead of the standard four. Hence, the recurrence becomes T(n) = 3T(n/2) + O(n) and solution of this recurrence is O(n1.59). This idea has been discussed more thoroughly in this article. Therefore the above problem can be solved using the steps below:
- Create a function findSum(), which finds the sum of two large numbers represented as strings. Similarly, create a function findDiff(), which finds the difference of two large numbers represented as strings.
- In the recursive function multiply(A, B), which multiplies the numbers using Karatsuba’s Algorithm, firstly append zeroes in front of A and B to make their digit count equal and even.
- Then calculate the values of Al, Ar, Bl, and Br as defined above and recursively find the values of multiply(Al, Bl), multiply(Ar, Br), and multiply((Al + Ar), (Bl + Br)) and plug their values in the above-derived equation.
- Print the answer to the equation after removing the leading zeroes from it.
Below is the implementation of the above approach:
Time Complexity: O(Nlog 3) or O(N1.59), where N is the maximum among the lengths given strings A and B.
Auxiliary Space: O(N2)