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?

  1. A. Yes, because i * i never exceeds 10^9
  2. 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
  3. C. No, because the loop never ends
  4. 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

Exams that ask this topic