GATE | GATE-CS-2015 (Set 1) | Question 65

Consider the following C function.

filter_none

edit
close

play_arrow

link
brightness_4
code

int fun1 (int n)
{
   int i, j, k, p, q = 0;
   for (i = 1; i<n; ++i)
   {
      p = 0;
      for (j = n; j > 1; j = j/2)
         ++p;
      for (k = 1; k < p; k = k*2)
         ++q;
   }
   return q;
}

chevron_right


Which one of the following most closely approximates the return value of the function fun1?
(A) n3
(B) n (logn)2
(C) nlogn
(D) nlog(logn)


Answer: (D)

Explanation:

int fun1 (int n)
{
   int i, j, k, p, q = 0;

   // This loop runs Θ(n) time
   for (i = 1; i < n; ++i)
   {
      p = 0;

      // This loop runs Θ(Log n) times. Refer this 
      for (j=n; j > 1; j=j/2)
         ++p;
     
      // Since above loop runs Θ(Log n) times, p = Θ(Log n)
      // This loop runs Θ(Log p) times which loglogn
      for (k=1; k < p; k=k*2)
         ++q;
   
   }
   return q;
}

T(n) = n(logn + loglogn)
T(n) = n(logn) dominant



But please note here we are return q which lies in loglogn so ans should be T(n) = nloglogn

Refer this for details.

Quiz of this Question



My Personal Notes arrow_drop_up