Search code examples
algorithmbig-ocomplexity-theorynested-loopscode-complexity

Nested loops, how many times run and complexity


I have these 2 codes, the question is to find how many times x=x+1 will run in each occasion as T1(n) stands for code 1 and T2(n) stands for code 2. Then I have to find the BIG O of each one, but I know how to do it, the thing is I get stuck in finding how many times ( as to n of course ) will x = x + 1 will run.

CODE 1:

for( i= 1; i <= n; i++)
    {
    for(j = 1; j <= sqrt(i); j++)
          {
           for( k = 1; k <= n - j + 1; k++)
               {
               x = x + 1;
               }
          }
    }

CODE 2:

for(j = 1; j <= n; j++)
   {
    h = n;
    while(h > 0)
        {
        for (i = 1; i <= sqrt(n); i++)
            {
            x = x+1;
            } 
        h = h/2;
        }

   }

I am really stuck, and have read already a lot so I ask if someone can help me, please explain me analytically.

PS: I think in the code 2 , this for (i = 1; i <= sqrt(n); i++) will run n*log(n) times, right? Then what?


Solution

  • For code 1 you have that the number of calls of x=x+1 is:

    enter image description here

    Here we bounded 1+sqrt(2)+...+sqrt(n) with n sqrt(n) and used the fact that the first term is the leading term.

    For code 2 the calculations are simpler:

    enter image description here enter image description here

    The second loop actually goes from h=n to 0 by iterating h = h/2 but you can see that this is the same as going from 1 to log n. What we used is the fact the j, t, i are mutually independent (analogously just like we can write that sum from 1 to n of f(n) is just nf(n)).