I need to write a recursive method that multiplies 2 square matrices (size n-by-n). It needs to run in theta(N^3) time but it's not Strassen's algorithm. I've written a method but I am getting a stack overflow.
Matrix A is Matrix B is
1 2 1 0 3 2 3 0
2 3 2 0 2 1 2 0
1 2 1 0 3 2 3 0
The two matrices are both int[][]. here is the code I have written:
public int[][] ncubed(int [][]A, int [][]B){
int w = A.length;
int [][] C = new int[w][w];
if (w==1){
C[0][0] = A[0][0] * B[0][0];
}
else{
int [][]A1 = partition(1,A);
int [][]A2 = partition(2,A);
int [][]A3 = partition(3,A);
int [][]A4 = partition(4,A);
int [][]B1 = partition(1,B);
int [][]B2 = partition(2,B);
int [][]B3 = partition(3,B);
int [][]B4 = partition(4,B);
int [][]C1 = partition(1,C);
int [][]C2 = partition(2,C);
int [][]C3 = partition(3,C);
int [][]C4 = partition(4,C);
C1 = add(ncubed(A1,B1),ncubed(A2,B3));
C2 = add(ncubed(A1,B2),ncubed(A2,B4));
C3 = add(ncubed(A3,B1),ncubed(A4,B3));
C4 = add(ncubed(A3,B2),ncubed(A4,B4));
join(C1, C, 0 , 0);
join(C2, C, w/2 , 0);
join(C3, C, 0, w/2);
join(C4, C, w/2, w/2);
}
return C;
}
public int [][] partition(int quadrant, int[][] array){
int n = array.length;
int[][] Q = new int[array.length][array.length];
if(quadrant>4 || quadrant<1) return null;
switch(quadrant){
case(1):
for(int i = 0; i<(n/2); i++){
for(int j = 0; j<(n/2); j++){
Q[i][j] = array[i][j];
}
}
break;
case(2):
for(int i = n/2; i<n; i++){
for(int j = 0; j<(n/2); j++){
Q[i][j] = array[i][j];
}
}
break;
case(3):
for(int i = 0; i<(n/2); i++){
for(int j = (n/2); j<n; j++){
Q[i][j] = array[i][j];
}
}
break;
case(4):
for(int i = (n/2); i<n; i++){
for(int j = (n/2); j<n; j++){
Q[i][j] = array[i][j];
}
}
break;
}
return Q;
}
The methods add and join work fine because I've tested them so it's not in that part. I just can't figure out my problem in the actual ncubed method(the matrix multiply method). If anyone is able to help me understand something I'm doing incorrectly or show me another way to do this with the specifications stated at the top, that would be awesome. Thanks for any help.