Skip to content

Commit 5d285df

Browse files
committed
Added Karatsuba's multiplication algorithm
1 parent df3900a commit 5d285df

File tree

1 file changed

+5
-6
lines changed

1 file changed

+5
-6
lines changed

src/main/java/com/thealgorithms/divideandconquer/KaratsubaMultiplication.java

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,33 @@
11
// Karatsuba Multiplication Algorithm
22
// Explanation: https://en.wikipedia.org/wiki/Karatsuba_algorithm
33

4-
54
import java.util.Scanner;
65

76
public class KaratsubaMultiplication {
87

8+
// Private constructor to prevent instantiation
9+
private KaratsubaMultiplication() {
10+
throw new UnsupportedOperationException("Utility class");
11+
}
12+
913
// Karatsuba multiplication function
1014
public static long karatsuba(long x, long y) {
11-
// Base case for recursion
1215
if (x < 10 || y < 10) {
1316
return x * y;
1417
}
1518

16-
// Calculate the size of the numbers
1719
int n = Math.max(Long.toString(x).length(), Long.toString(y).length());
1820
int m = n / 2;
1921

20-
// Split the digit sequences about the middle
2122
long high1 = x / (long) Math.pow(10, m);
2223
long low1 = x % (long) Math.pow(10, m);
2324
long high2 = y / (long) Math.pow(10, m);
2425
long low2 = y % (long) Math.pow(10, m);
2526

26-
// 3 recursive calls
2727
long z0 = karatsuba(low1, low2);
2828
long z1 = karatsuba(low1 + high1, low2 + high2);
2929
long z2 = karatsuba(high1, high2);
3030

31-
// Combine the results
3231
return (z2 * (long) Math.pow(10, 2 * m)) + ((z1 - z2 - z0) * (long) Math.pow(10, m)) + z0;
3332
}
3433

0 commit comments

Comments
 (0)