ProgrammingVery hard

A binary search on the answer in [1, 10^18] computes mid = (lo + hi) / 2 with long long. Is this safe?

  1. A. No, because lo + hi always overflows long long
  2. B. Safe for these bounds, since lo + hi stays below 2 x 10^18, although lo + (hi - lo) / 2 is the habit that works for any bound
  3. C. No, because division is undefined on long long
  4. D. Yes, because long long never overflows

Correct answer: B. Safe for these bounds, since lo + hi stays below 2 x 10^18, although lo + (hi - lo) / 2 is the habit that works for any bound

For bounds up to 10^18, lo + hi is about 2 x 10^18, which fits in signed 64-bit. The form lo + (hi - lo) / 2 is safer for any bound.

More C Programming questions

Exams that ask this topic