ADVANCED DATA STRUCTURES PROGRAM • LEVEL 13 — ADVANCED SEARCHING
Binary-Search an Integer Square Root
Learn how to binary-search an integer square root using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
Floor square root = 7
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
long long number = 50, low = 0, high = number, answer = 0;
while (low <= high) { long long middle = low + (high - low) / 2; if (middle <= number / (middle ? middle : 1)) { answer = middle; low = middle + 1; } else high = middle - 1; }
printf("Floor square root = %lld\n", answer); return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Floor square root = 7
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Search the monotonic answer space for the greatest integer whose square does not exceed the input.
- Display the computed result.
Search the monotonic answer space for the greatest integer whose square does not exceed the input.
EFFICIENCY
Time and space complexity
Time complexity
O(log n)
Auxiliary space
O(1)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
