1

Let's consider the following algorithm to multiply squares matrix: A is a matrix of NxN. r_i, r_j defines interval of rows. For example r_i = 2, r_j=3 means the second and the third rows. c_i, c_j means the same as r_i, r_j but for columns. We assume that N = 2^s for some s.

mul(A, B, r_i, r_j, c_i, c_j){
if(r_i != r_j){
   r_m = floor((r_i+r_j)/2)

   mul(A, B,  r_i, r_m, c_i, c_j) 
   mul(A, B, r_m+1, r_j, c_i, c_j)
} else if(c_i != c_j){   
   c_m = floor((c_i+c_j)/2)
   mul(A, B, r_i,r_j, c_i, c_m)
   mul(A, B, r_i, r_j, c_m+1, c_j)
}else{
 for i = 1 to N:
    C[r_i][c_i] += A[r_i][i] * B[i][c_i] 
 }

}

And the most important:

Complexity of that algorithm takes: T(n) = 4T(n/2) + n = O(n^2)

And it is not correct. The correct answer is O(n^3). Why my computation is incorrect.

Raphael
  • 72,336
  • 29
  • 179
  • 389
Logic
  • 319
  • 1
  • 10

2 Answers2

1

Your calculation is not right... $$ U(R,C) = 2U(\frac{R}{2},C)\textrm{ or } 2U(R,\frac{C}{2})\\ U(1,1) = O(n) $$

Basically, you have $N^2$ unique positions (which you drive your way down to recursively, rather than just looping) - for each of those you do a loop of O(N) so you have $O(N^3)$

MotiNK
  • 551
  • 2
  • 12
0

Your algorithm can be unrolled to the usual $O(N^3)$ matrix multiplication algorithm. If you open up all the recursive steps you will get a recursion tree whose $N^2$ leaves are of the form mul(A, B, r, r, c, c), each of which has running time $\Theta(N)$, for a total of $\Theta(N^3)$.

Yuval Filmus
  • 276,994
  • 27
  • 311
  • 503