GATE | GATE-CS-2015 (Set 1) | Question 65
Consider the following C function.
C
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;
}
Which one of the following is the time complexity for 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.
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
Hence, time complexity will be T(n) = nloglogn
Quiz of this Question
Please comment below if you find anything wrong in the above post
Last Updated :
16 Nov, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...