Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. import java.util.Arrays;
  2.  
  3. public class MatrixMultiplicationRecursive {
  4.  
  5. public static void main(String[] args) {
  6. int[][] A = new int[][]{{13, -3, -25, 20}, {-3, -16, -23, 18}, {20, -7, 12, -5}, {-22, 15, -4, 7}};
  7. int[][] B = new int[][]{{13, 10, 11, 12}, {13, 14, -23, 18}, {20, -7, 12, -11}, {-12, -13, -14, 7}};
  8. System.out.println(Arrays.deepToString(
  9. multiply(A, B, 0, 0, 0, 0, A.length)
  10. ));
  11. }
  12.  
  13. public static int[][] multiply(int[][] A, int[][] B, int rowA, int colA,
  14. int rowB, int colB, int size) {
  15. int[][] C = new int[size][size];
  16. if (size == 1) {
  17. C[0][0] = A[rowA][colA] * B[rowB][colB];
  18. } else {
  19. int newSize = size / 2;
  20. // C11 = A11 * B11 + A12 * B21
  21. add(C, multiply(A, B, rowA, colA, rowB, colB, newSize),//A11*B11
  22. multiply(A, B, rowA, colA + newSize, rowB + newSize, colB, newSize), //A12*B21
  23. 0, 0);//C11
  24.  
  25. // C12 = A11 * B12 + A12 * B22
  26. add(C, multiply(A, B, rowA, colA, rowB, colB + newSize, newSize),//A11*B12
  27. multiply(A, B, rowA, colA + newSize, rowB + newSize, colB + newSize, newSize),//A12*B22
  28. 0, newSize);//C12
  29.  
  30. // C21 = A21 * B11 + A22 * B21
  31. add(C, multiply(A, B, rowA + newSize, colA, rowB, colB, newSize),//A21*B11
  32. multiply(A, B, rowA + newSize, colA + newSize, rowB + newSize, colB, newSize),//A22*B21
  33. newSize, 0);//C21
  34.  
  35. // C22 = A21 * B12 + A22 * B22
  36. add(C, multiply(A, B, rowA + newSize, colA, rowB, colB + newSize, newSize),//A21*B12
  37. multiply(A, B, rowA + newSize, colA + newSize, rowB + newSize, colB + newSize, newSize), //A22*B22
  38. newSize, newSize);//C22
  39. }
  40.  
  41. return C;
  42. }
  43.  
  44. /**
  45. * @param C Matrix of size n x n to add to
  46. * @param A A matrix of size n/2 x n/2 to add from
  47. * @param B A matrix of size n/2 x n/2 to add from
  48. * @param rowC The starting row of the C matrix
  49. * @param colC The starting column of the C matrix
  50. */
  51. private static void add(int[][] C, int[][] A, int[][] B, int rowC, int colC) {
  52. int n = A.length;
  53. for (int i = 0; i < n; i++) {
  54. for (int j = 0; j < n; j++) {
  55. C[i + rowC][j + colC] = A[i][j] + B[i][j];
  56. }
  57. }
  58.  
  59. }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement