Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Big O notation of 3 nested loops of log(n)

What would the Big O notation be for the following nested loops?

     for (int i = n; i > 0; i = i / 2){
        for (int j = n; j > 0; j = j / 2){
           for (int k = n; k > 0; k = k / 2){
              count++;
           }
        }
     }

My thoughts are: each loop is O(log2(n)) so is it as simple as multiply

O(log2(n)) * O(log2(n)) * O(log2(n))  =  O(log2(n)^3)
like image 420
Kailua Bum Avatar asked Jan 23 '13 06:01

Kailua Bum


1 Answers

Yes, that is correct.

One way to figure out the big-O complexity of nested loops whose bounds do not immediately depend on one another is to work from the inside out. The innermost loop does O(log n) work. The second loop runs O(log n) times and does O(log n) work each time, so it does O(log2 n) work. Finally, the outmost loop runs O(log n) times and does O(log2 n) work on each iteration, so the total work done is O(log3 n).

Hope this helps!

like image 97
templatetypedef Avatar answered Sep 27 '22 16:09

templatetypedef