|
| 1 | +import java.util.Scanner; |
| 2 | + |
| 3 | +public class KaratsubaMultiplication { |
| 4 | + |
| 5 | + // Karatsuba multiplication function |
| 6 | + public static long karatsuba(long x, long y) { |
| 7 | + // Base case for recursion |
| 8 | + if (x < 10 || y < 10) { |
| 9 | + return x * y; |
| 10 | + } |
| 11 | + |
| 12 | + // Calculate the size of the numbers |
| 13 | + int n = Math.max(Long.toString(x).length(), Long.toString(y).length()); |
| 14 | + int m = n / 2; |
| 15 | + |
| 16 | + // Split the digit sequences about the middle |
| 17 | + long high1 = x / (long) Math.pow(10, m); |
| 18 | + long low1 = x % (long) Math.pow(10, m); |
| 19 | + long high2 = y / (long) Math.pow(10, m); |
| 20 | + long low2 = y % (long) Math.pow(10, m); |
| 21 | + |
| 22 | + // 3 recursive calls |
| 23 | + long z0 = karatsuba(low1, low2); |
| 24 | + long z1 = karatsuba(low1 + high1, low2 + high2); |
| 25 | + long z2 = karatsuba(high1, high2); |
| 26 | + |
| 27 | + // Combine the results |
| 28 | + return (z2 * (long) Math.pow(10, 2 * m)) + ((z1 - z2 - z0) * (long) Math.pow(10, m)) + z0; |
| 29 | + } |
| 30 | + |
| 31 | + public static void main(String[] args) { |
| 32 | + Scanner sc = new Scanner(System.in); |
| 33 | + |
| 34 | + System.out.print("Enter first number: "); |
| 35 | + long num1 = sc.nextLong(); |
| 36 | + |
| 37 | + System.out.print("Enter second number: "); |
| 38 | + long num2 = sc.nextLong(); |
| 39 | + |
| 40 | + long result = karatsuba(num1, num2); |
| 41 | + |
| 42 | + System.out.println("Product: " + result); |
| 43 | + |
| 44 | + sc.close(); |
| 45 | + } |
| 46 | +} |
| 47 | + |
0 commit comments