Related Articles

# GATE | GATE-CS-2017 (Set 2) | Question 49

• Difficulty Level : Medium
• Last Updated : 28 Jun, 2021

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)

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

Attention reader! Don’t stop learning now.  Practice GATE exam well before the actual exam with the subject-wise and overall quizzes available in GATE Test Series Course.

Learn all GATE CS concepts with Free Live Classes on our youtube channel.

My Personal Notes arrow_drop_up