Advertisement
VladNitu

Karatsuba DC

Dec 14th, 2022
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.97 KB | None | 0 0
  1. private static int nDigits(long x) {
  2. int digits = 0;
  3. do {
  4. digits++;
  5. x /= 10;
  6. } while (x != 0);
  7. return digits;
  8. }
  9.  
  10. private static long multiply(long x, long y) {
  11. // x = a * 10^(N/2) + b;
  12. // y = c * 10^(N / 2) + d
  13. int N = nDigits(x);
  14.  
  15. if (N == 1)
  16. return x * y;
  17.  
  18. //Divide
  19. int digits = (int) Math.pow(10, N / 2);
  20. long a = x / digits;
  21. long b = x % digits;
  22.  
  23. long c = y / digits;
  24. long d = y % digits;
  25.  
  26. // Solve
  27. long p1 = multiply(a, c);
  28. long p2 = multiply(b, d);
  29. long aux = multiply(a + b, c + d);
  30. long p3 = aux - p1 - p2;
  31.  
  32. return (p1 * (long) Math.pow(10, N) + p3 * (long) Math.pow(10, N / 2) + p2);
  33. }
  34.  
  35. public static void main(String[] args) {
  36. long x = 1234;
  37. long y = 5678;
  38. System.out.println(multiply(x, y));
  39. }
  40. }
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement