Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble Finding Big O Time for this loop

Tags:

big-o

I'm trying to find the Big O running time for the following code snippet:

for( i = 0; i < n * n; i++ )
    for( j = 0; j < i; j++ )
        k++;

I'm not sure if it would be O(n^3) because of the multiplication of n, or just O(n^2). Some help would be appreciated :)

like image 956
David Undy Avatar asked Dec 27 '22 02:12

David Undy


2 Answers

The inner loop will execute exactly 0 + 1 + ... + n^2 - 2 + n^2 - 1 = (n^2)(n^2 - 1)/2 times (see Arithmetic Series), so it's actually O(n^4).

like image 75
Taylor Brandstetter Avatar answered Mar 27 '23 17:03

Taylor Brandstetter


for(i := 1 -> n ){
 for(j := 1 -> i ){
  something
 }
}

runs in O(n^2)[innermost loop runs 1,2,3....n times as the value of n increases, so in total it runs for a sum of 1+2+3...+n = O(n^2)]

in your sample code let i := 1 -> p where p = O(n^2) then since the code runs in O(p^2) its running time will be O(n^4)

Using the Big-O notation can help you through some situations. Consider this :
for(i =n/2; i < n; i++){
 for(j = 2; j < n; j=j*2){
  something
 }
}

the outer loop runs O(n) and the inner loop runs O(log(n))[ see it as constantly dividing n by 2 : definition of log]
so the total running time is : O(n(logn))

like image 20
jemmanuel Avatar answered Mar 27 '23 16:03

jemmanuel