|
1 | 1 | // Karatsuba Multiplication Algorithm |
2 | 2 | // Explanation: https://en.wikipedia.org/wiki/Karatsuba_algorithm |
3 | 3 |
|
4 | | - |
5 | 4 | import java.util.Scanner; |
6 | 5 |
|
7 | 6 | public class KaratsubaMultiplication { |
8 | 7 |
|
| 8 | + // Private constructor to prevent instantiation |
| 9 | + private KaratsubaMultiplication() { |
| 10 | + throw new UnsupportedOperationException("Utility class"); |
| 11 | + } |
| 12 | + |
9 | 13 | // Karatsuba multiplication function |
10 | 14 | public static long karatsuba(long x, long y) { |
11 | | - // Base case for recursion |
12 | 15 | if (x < 10 || y < 10) { |
13 | 16 | return x * y; |
14 | 17 | } |
15 | 18 |
|
16 | | - // Calculate the size of the numbers |
17 | 19 | int n = Math.max(Long.toString(x).length(), Long.toString(y).length()); |
18 | 20 | int m = n / 2; |
19 | 21 |
|
20 | | - // Split the digit sequences about the middle |
21 | 22 | long high1 = x / (long) Math.pow(10, m); |
22 | 23 | long low1 = x % (long) Math.pow(10, m); |
23 | 24 | long high2 = y / (long) Math.pow(10, m); |
24 | 25 | long low2 = y % (long) Math.pow(10, m); |
25 | 26 |
|
26 | | - // 3 recursive calls |
27 | 27 | long z0 = karatsuba(low1, low2); |
28 | 28 | long z1 = karatsuba(low1 + high1, low2 + high2); |
29 | 29 | long z2 = karatsuba(high1, high2); |
30 | 30 |
|
31 | | - // Combine the results |
32 | 31 | return (z2 * (long) Math.pow(10, 2 * m)) + ((z1 - z2 - z0) * (long) Math.pow(10, m)) + z0; |
33 | 32 | } |
34 | 33 |
|
|
0 commit comments