GATE | GATE-CS-2017 (Set 2) | Question 49
Consider the following C function.
int fun(int n)
{
int i, j;
for (i = 1; i <= n ; i++)
{
for (j = 1; j < n; j += i)
{
printf("%d %d", i, j);
}
}
}
Time complexity of fun in terms of θ notation is:
(A) θ(n √n)
(B) θ(n2)
(C) θ(n log n)
(D) θ(n 2 log n)
Answer: (C)
Explanation: Let us see how many times the innermost statement “printf(“%d %d”, i, j);” is executed.
For i = 1, the statement runs n times
The i’th iteration, statement runs Θ(n/i) times.
Summing all iterations for i = 1 to n, we get
Thus T(n) = Θ(n(1 + 1/2 +1/3 + ….)) = Θ(n log n).
Note that the value of 1/1 + 1/2 + 1/3 + …. 1/n is approximately same as Log n for large values of n.
Quiz of this Question
Last Updated :
28 Jun, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...