ProgrammingVery hard
A binary search on the answer in [1, 10^18] computes mid = (lo + hi) / 2 with long long. Is this safe?
- A. No, because lo + hi always overflows long long
- 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
- C. No, because division is undefined on long long
- 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
- A sum of n = 10^5 terms is stored in a double. Is this a safe choice for exact integer sums up to 10^14?
- A loop reads n numbers and stores them in int a[n] as a VLA of size up to 10^6 inside main. What is the main risk?
- To sort 10^6 integers with qsort, which comparator is correct for all int values?
- A counting pass over an array of 10^7 values, each in [0, 9], uses 10 counters. Which statement is correct?
- Which output method is fast enough for 10^6 lines of output in C?
- Which 2D DP table declaration is correct for a 1000 x 1000 table of ints in a contest C program?