Machine-translated by Google. Questions are authored in English.
Top

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

  • A.4
  • B.5
  • C.6
  • D.40

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.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.