29-Karatsuba Algorithm-23-05-2023
29-Karatsuba Algorithm-23-05-2023
29-Karatsuba Algorithm-23-05-2023
URL:https://forms.gle/2Qag3HhHTrpx5fna8
QR CODE:
KARATSUBA
ALGORITHM
Karatsuba Algorithm
Introduction
Introduction
Naive Method
The naive method is to follow the elementary school
multiplication method, i.e. to multiply each digit of the
second number with every digit of the first number and
then add all the multiplication results.
This algorithm takes O(n2) time.
Naive Method Karatsuba Algorithm
public static int multiplication(int X, int Y) { carry = num / 10;
// Convert numbers into string }
String x = Integer.toString(X); // else the digit is append to the
String y = Integer.toString(Y); intermediate result
int result = 0; // And assign carry as zero
// Looping over y else {
for (int i = 0; i < y.length(); i++) { inter_res =
int carry = 0; // intermediate carry Integer.toString(num) + inter_res;
String inter_res = ""; // intermediate carry = 0;
result }
// Looping over x. }
for (int j = x.length() - 1; j >= 0; j--) { // Adding the intermediate
// intermediate multiplication of each results
digit and addition of carry. result *= 10;
int num = result +=
Character.getNumericValue(y.charAt(i)) * Integer.parseInt(inter_res);
Character.getNumericValue(x.charAt(j)) + carry; }
if (num > 9 && j > 0) { System.out.print("result: ");
inter_res = Integer.toString(num % 10) return result;
+ inter_res; }}
Karatsuba Algorithm
Karatsuba Algorithm
Let’s consider two 4-digit numbers x and y where x=1234
and y=5678.
First of all, we should divide the n-digit numbers into
n/2-digit numbers as shown below.
X = 12 34 Y = 23 45
Steps:
Step 1: Compute a.c = 12 x 23 = 276
Step 2: Compute b.d = 34 x 45 = 1530
Step 3: Compute (a+b)(c+d) = 46 x 68 = 3128
Step 4: Compute (3) - (2) - (1) = 3128 - 1530 - 276 = 1322
Finally, multiply the output of step 1 by 10000 (104), the output of step 4 by
100 (102), and add them both with the output of step 2.
Result: 2760000 + 132200 + 1530 = 2893730
The product of 1234 and 2345 using the Karatsuba algorithm is 2897730.
Karatsuba Algorithm
compute the product of 23 and 67 using the Karatsuba algorithm.
a b c d
X = 2 3 Y = 6 7
Time Complexity
Time Complexity
Karatsuba Algorithm
Implementation
Algorithm
1. Compute starting set (a*c)
2. Compute set after starting set may it be ending set (b*d)
3. Compute starting set with ending sets (a+b)(c+d)
4. Subtract values of Step 3 from Step 2 from Step 1
5. Add all the values with the following modifications:-
1. Pad up 10n to the number obtained from Step 1
2. Step 2 value unchanged
3. Pad up 10n/2 to the value obtained from Step 4.
Karatsuba Algorithm
Program
Sample IO
Karatsuba Multiplication Algorithm Test
https://learn.codemithra.com