Java Program to Implement the Karatsuba Multiplication Algorithm
It is a replacement for the grade school algorithm for multiplying numbers. of bigger digits. The Karatsuba Algorithm for fast multiplication algorithm using Divide and Conquer developed by Anatolii Alexeevitch Karatsuba in 1960. The first thing that hits the head what is it and why it is designed. Though there are 3 ways to multiply numbers :
- Third-grade school algorithm Method (Standard-way)
- Recursive algorithm Method
- Karatsuba Multiplication Method
Why the Karatsuba algorithm?
The goal of the algorithm is designed because the design space is surprisingly rich. Its time complexity is follows and do not it as time complexity for this is very important and is sometimes do asked in interview questions.
O(n^log2(3)) time (~ O(n^1.585))
Where n is the number of digits of the numbers multiplying. It is discussed by multiplying two big integer numbers to show internal working step by step. The goal is to reduce the space complexity for which the integer numbers terms will be broken down in such a way to x and y are broken into a set of digits as the logic behind it is divide and conquer. If the numbers are smaller there is no need to multiply, standard mutilation of two integers is preferred.
The algorithm is standardized for 4 digits for sake of understanding. One can multiply as many digits taken into sets.
- Compute starting set (a*c)
- Compute set after starting set may it be ending set (b*d)
- Compute starting set with ending sets
- Subtract values of step 3 from step2 from step1
- Pad up (Add) 4 zeros to the number obtained from Step1, step2 value unchanged, and pad up two zeros to value obtained from step4.
Now let us do propose the above steps and showing it with an illustration prior getting to the implementation part
Input: x = 1234, y = 5678
Processing: As per above inputs x = 1234 y = 5678 a = 12, b = 34 c = 56, d = 78 Step 1: a * c = 172 Step 2: b * d = 2652 Step 3: (a+b)(c+d) = 134 * 36 = 6164 Step 4: 6164 - 2652 - 172 = 2840 Step 5: 1720000 + 2652 + 284000 = 7006652
The value obtained from step 5 is in fact the product obtained if standard school multiplication is carried on between these two numbers ‘x’ and ‘y’.
1720000 + 2652 + 284000 = 7006652
Implementation: Note not to grasp the formulas laid down for this algorithm rather understanding it in this way makes its way to better.
Product 1 : 85348320 Product 2 : 21726
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections 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.