|
| 1 | +// Karatsuba Multiplication Algorithm |
| 2 | +// |
| 3 | +// -----References----- |
| 4 | +// https://en.wikipedia.org/wiki/Karatsuba_algorithm |
| 5 | +// https://www.geeksforgeeks.org/dsa/karatsuba-algorithm-for-fast-multiplication-using-divide-and-conquer-algorithm/ |
| 6 | + |
| 7 | +import java.util.Scanner; |
| 8 | + |
| 9 | +public final class KaratsubaMultiplication { |
| 10 | + |
| 11 | + // Private constructor to prevent instantiation |
| 12 | + private KaratsubaMultiplication() { |
| 13 | + throw new UnsupportedOperationException("Utility class"); |
| 14 | + } |
| 15 | + |
| 16 | + // Karatsuba multiplication function |
| 17 | + public static long karatsuba(long x, long y) { |
| 18 | + if (x < 10 || y < 10) { |
| 19 | + return x * y; |
| 20 | + } |
| 21 | + |
| 22 | + int n = Math.max(Long.toString(x).length(), Long.toString(y).length()); |
| 23 | + int m = n / 2; |
| 24 | + |
| 25 | + long high1 = x / (long) Math.pow(10, m); |
| 26 | + long low1 = x % (long) Math.pow(10, m); |
| 27 | + long high2 = y / (long) Math.pow(10, m); |
| 28 | + long low2 = y % (long) Math.pow(10, m); |
| 29 | + |
| 30 | + long z0 = karatsuba(low1, low2); |
| 31 | + long z1 = karatsuba(low1 + high1, low2 + high2); |
| 32 | + long z2 = karatsuba(high1, high2); |
| 33 | + |
| 34 | + return (z2 * (long) Math.pow(10, 2 * m)) + ((z1 - z2 - z0) * (long) Math.pow(10, m)) + z0; |
| 35 | + } |
| 36 | + |
| 37 | + public static void main(String[] args) { |
| 38 | + Scanner sc = new Scanner(System.in); |
| 39 | + |
| 40 | + System.out.print("Enter first number: "); |
| 41 | + long num1 = sc.nextLong(); |
| 42 | + |
| 43 | + System.out.print("Enter second number: "); |
| 44 | + long num2 = sc.nextLong(); |
| 45 | + |
| 46 | + long result = karatsuba(num1, num2); |
| 47 | + |
| 48 | + System.out.println("Product: " + result); |
| 49 | + |
| 50 | + sc.close(); |
| 51 | + } |
| 52 | +} |
0 commit comments