Question
Consider the following C code. Assume that unsigned long int type length is 64 bits.
unsigned long int fun(unsigned long int n){
unsigned long int i, j = 0, sum = 0;
for (i = n; i > 1; i = i/2) j++;
for ( ; j > 1; j = j/2) sum++;
return(sum);
}
The value returned when we call fun with the input is
Official answer and solution
- Official answer
- B
- From
- Official GATE 2018 answer key
Solution
Determine the number of loop iterations as successive base-2 logarithms of the input.
Analyze the first loop:
for (i = n; i > 1; i = i/2) j++;
With , starts at and halves each iteration until .
The sequence of values of before halting is , executing exactly 40 iterations. Thus, .
Analyze the second loop:
for ( ; j > 1; j = j/2) sum++;
Trace starting with and :
- Iteration 1: ,
- Iteration 2: ,
- Iteration 3: ,
- Iteration 4: ,
- Iteration 5: ,
At , condition fails and the loop halts.
The function returns .
B
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2018 Computer Science and Information Technology (CS)
- Question
- 42 of 65, printed as CS Q.32
- 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.