Discussion
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 \(\gt\) 1; i = i/2) j++;
for ( ; j \(\gt\) 1; j = j/2) sum++;
return(sum);
}
The value returned when we call fun with the input \(2^{40}\) is
Answer: B
The function returns 5.
The first loop halves i from \(2^{40}\) until it reaches 1, counting the halvings: j ends as 40, which is \(\log_{2} n\).
The second loop halves j while it is greater than 1, counting in sum: j goes 40, 20, 10, 5, 2, 1. The body runs for 40, 20, 10, 5 and 2, so sum is 5, which is \(\lfloor \log_{2} 40 \rfloor\).
40 is the value of j after the first loop, not the returned sum. 4 and 6 come from miscounting the halvings: integer division takes 5 to 2 and 2 to 1, so the body runs at 5 and at 2 but not at 1.
Post your comment
Please log in or register to post a comment.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development