ProgrammingVery hard
A counting loop uses the expression i * i <= n with int i and n up to 2^31 - 1. Is the loop correct?
- A. Yes, because i * i never exceeds 10^9
- B. No: once i reaches 46341, i * i exceeds INT_MAX, which is undefined, so use a long long i or the test i <= n / i
- C. No, because the loop never ends
- D. Yes, because int multiplication wraps in C
Correct answer: B. No: once i reaches 46341, i * i exceeds INT_MAX, which is undefined, so use a long long i or the test i <= n / i
46341 squared is just above INT_MAX, so the test overflows before the loop reaches sqrt(n) for n near 2^31. Use a long long for i or test i <= n / i.
More C Programming questions
- To read a whole line of unknown length in standard C without overflow, which approach is correct?
- A program sums the digits of 10^5 numbers with one loop per number that divides by 10. What is the total cost, about?
- A queue for BFS on a grid of 10^6 cells uses a fixed array of size 10^6 indexed by head and tail. Is this enough?
- To find the maximum over 10^5 queries of ranges in a static array, which approach is fast enough?
- A program multiplies two n x n matrices with n = 500 in int, and the product entries reach about 10^12. What is the error?
- To answer 'how many times does x appear in a sorted array' in O(log n), which pair of searches is correct?