0

I saw the same question 3 times on Stack Overflow: Complexity of an algorithm Time complexity for two pieces of code Tricky Big-O complexity

I wanted to ask the question in one of them but I couldn't since I'm new on the website and can't comment.

Can someone please explain to me why the complexity is O(logm + logn) and not O(logm * logn)? I tried solving it myself and O(logm * logn) makes more sense to me... since if for example you run it with n=16 and m=1000 then you get about 6 + 4... and it makes more sense that it'll run 6 * 4 times ...

Can you please clarify it for me..? Thanks :)

Community
  • 1
  • 1
unknown2u
  • 13
  • 3
  • The answer to the first link explains it... – user253751 Apr 19 '14 at 09:15
  • 1
    There's a sudden flood of Big-O questions. Aren't you taught anything in the class? – devnull Apr 19 '14 at 09:15
  • @devnull I think we really need an FAQ-type question for this that we can just VTC pretty much anything as a duplicate of. – Bernhard Barker Apr 19 '14 at 09:19
  • 1
    The while loop runs in O(log m), the for loop runs in O(log n), if it's not nested, you add the complexity - which part don't you understand? – Bernhard Barker Apr 19 '14 at 09:20
  • possible duplicate of [Complexity of an algorithm](http://stackoverflow.com/questions/22785650/complexity-of-an-algorithm) – Lorenz Meyer Apr 19 '14 at 18:57
  • Another interesting bit of math is that O(log(n) + log(m)) is O(log(n*m)). – Nuclearman Apr 20 '14 at 01:07
  • 1
    As I said I wanted to ask this question in the comments but I can't due to low reputation since I'm new... sorry. And as for your question devnull, you'd be surprised how some institutions teach... – unknown2u Apr 20 '14 at 06:26

2 Answers2

1

Well, the while loop runs in O(logm), where the log has a base of 3 and after the while loop, the outer for loop runs a constant number of times <= 100, and the inner for loop runs in O(logn), where the log has a base of 2.

Because it runs in O(1), the outer for loop can be ingnored( complexity means ignoring the constants and studying growth, not the number of steps in which an algorithm executes! ); the algorithm has O(logm + logn) complexity because first you have the while in O(logm) and after that the for in O(logn)( you do nat have the for inside the while to multiply them ).

Valdrinium
  • 1,398
  • 1
  • 13
  • 28
  • Right! Thanks, my bad. The while loop is the one that runs log_3(m) times and the first for loop runs according to the result of the while loop... Sorry, I didn't notice :) – unknown2u Apr 20 '14 at 06:23
1

while and for loops are two seperate loops. for is not inner loop. The code is like this

while (i>100){
    i = i/3;
} //end of while

for (int k=i; k>=0; k--){
    for (int j=1; j<n; j*=2)
        System.out.print(k + "\t" + j);
    System.out.println();
} //end of for

Since they are separate, result should be summed, not multiplied

smttsp
  • 4,011
  • 3
  • 33
  • 62