Question
Consider the following C function:
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 most closely approximates the return value of the function fun1?
Official answer and solution
- Official answer
- D
- From
- Official GATE 2015 answer key
Solution
Trace the step counts of nested loops in terms of input size n.
Analyzing the nested loops of fun1(n):
-
Outer loop:
for (i = 1; i < n; ++i)executes times. -
First inner loop:
for (j = n; j > 1; j = j / 2) ++p;
This loop repeatedly divides by 2 starting from until .
The number of iterations is . -
Second inner loop:
for (k = 1; k < p; k = k * 2) ++q;
This loop starts with and doubles until .
The number of increments to in one outer iteration is . -
Total return value:
Summing over all iterations of the outer loop:
This matches option D.
D
Confusing the doubling of with linear incrementation, which would erroneously yield .
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2015 Computer Science and Information Technology (CS) Session 1
- Question
- 41 of 65, printed as CS Q.31
- 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.