ProgrammingHardProduct company OA

What is printed?

What is printed?
int isqrt(int n) {
    int lo = 0, hi = n, r = 0;
    while (lo <= hi) {
        int m = lo + (hi - lo) / 2;
        if ((long long)m * m <= n) { r = m; lo = m + 1; }
        else hi = m - 1;
    }
    return r;
}
int main(void) { printf("%d %d %d", isqrt(99), isqrt(100), isqrt(1)); }
  1. A. 10 10 1
  2. B. 9 10 1
  3. C. 9 10 0
  4. D. 9 9 1

Correct answer: B. 9 10 1

The binary search keeps r as the largest m with m² ≤ n, i.e. the floor of the square root: 9 for 99, 10 for 100, 1 for 1. The cast to long long keeps m * m from overflowing for large n.

More C Programming questions

Exams that ask this topic