Question
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
Official answer and solution
- Official answer
- C
- From
- Official GATE 2017 answer key
Solution
Formulate the exact double summation for the number of print statements executed and evaluate the sum using the harmonic series.
Examine the nested loops:
- The outer loop runs for .
- For a given , the inner loop initializes , continues while , and increments by at each step (
j += i).
The values taken by are such that .
The number of iterations for a given is:
Summing the total number of iterations over all from 1 to :
Recall that .
Therefore, the total time complexity is:
This matches option C.
C
Assuming the inner loop always runs times regardless of , which would erroneously give .
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2017 Computer Science and Information Technology (CS) Session 2
- Question
- 38 of 65, printed as CS Q.38
- Section
- Computer Science and Information Technology
Report an error in this question
GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.