You are on page 1of 1

import java.util.

Scanner;

public class KaratsubaMultiplication {


public static long multiplication(long x, long y) {
if (x < 10 || y < 10) {
return x * y;
}

int n = Math.max(String.valueOf(x).length(), String.valueOf(y).length());


int nHalf = n / 2;

long a = x / (long) Math.pow(10, nHalf);


long b = x % (long) Math.pow(10, nHalf);
long c = y / (long) Math.pow(10, nHalf);
long d = y % (long) Math.pow(10, nHalf);

long ac = multiplication(a, c);


long bd = multiplication(b, d);
long adPlusBc = multiplication(a + b, c + d) - ac - bd;

long result = ac * (long) Math.pow(10, 2 * nHalf) + adPlusBc * (long) Math.pow(10, nHalf) +


bd;

return result;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the first number: ");


long num1 = scanner.nextLong();

System.out.print("Enter the second number: ");


long num2 = scanner.nextLong();

long product = multiplication(num1, num2);


System.out.println("The result of multiplication is: " + product);
}
}

You might also like