Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Big-O calculation

Tags:

big-o

I am aware intuitively that two for loops make an O(n^2) function, but what if the loops are unrelated. How is it expressed

For example:

for(x = 1; x < t; x++)
    for(y = 1; y < z; y++)
            do something trivial
    end
end

is the big-o of this O(t*z)? or is it O(n^2) or is it O(t^2). I have always overlooked this, but I would like to know now.

Thanks

like image 467
richsoni Avatar asked Jul 21 '26 00:07

richsoni


2 Answers

It's O(t*z). If you have two nested loop each doing n iterations you have n^2 because of n*n :)

It's like computing the area.. for every t you iterate z times.. so it's intuitively t*z..

Or you can imagine to have a counter inside the loops.. how much will be the result?

like image 124
duedl0r Avatar answered Jul 26 '26 17:07

duedl0r


for(x = 1; x < t; x++)
    for(y = 1; y < z; y++)
            do something trivial
    end
end

As written, these loops execute (t-1)*(z-1) = t*z - t - z + 1 times -> O(t*z)

like image 40
duffymo Avatar answered Jul 26 '26 15:07

duffymo