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)); }- A. 10 10 1
- B. 9 10 1
- C. 9 10 0
- 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
- What is printed? c struct N { struct N nx; } n[5]; for (int i = 0; i < 4; i++) n[i].nx = &n[i + 1]; n[4].nx = &n[2]; struct N s = n, f =…
- On a two's-complement machine with C99 division, what is printed? c printf("%d %d", -13 % 8, -13 & 7);
- Assume IEEE-754 single-precision float and 32-bit unsigned int. What is printed? c union { float f; unsigned u; } v = {1.0f}…
- What is printed? c #line 100 int a = LINE; int b = LINE; printf("%d %d", a, b);
- What is printed? c #define CAT(a, b) a##b printf("%d", CAT(1, 2) + CAT(0x, 1F));
- What is printed? c #define f(x) ((x) 2) int (f)(int x) { return x + 100; } int main(void) { printf("%d %d", f(1), (f)(1)); }