Consider the following C function.

int fun1 (int n)
{
int i, j, k, p, q = 0;
for (i = 1; i 1; j = j/2)
++p;
for (k = 1; k < p; k = k*2) ++q; } return q; } [/sourcecode] 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


  • Last Updated : 16 Nov, 2018

Share your thoughts in the comments