Challenge: Integer Square Root
Completed
Read n and print the largest whole number r with r × r ≤ n, using binary search on the answer (no sqrt).
Input
One whole number n (0 ≤ n ≤ 1018).
Output
One number.
Example
Input
50
Output
7
Editor
C++
Hints
The answer is between 0 and 10⁹.
Check mid <= n / mid instead of mid * mid <= n to avoid overflow.
Solution explanation
About 30 steps for any n up to 10¹⁸.
Show solution
#include <iostream>
using namespace std;
int main() {
long long n;
cin >> n;
long long lo = 0, hi = 1000000000LL;
while (lo < hi) {
long long mid = lo + (hi - lo + 1) / 2;
if (mid <= n / mid) lo = mid;
else hi = mid - 1;
}
cout << lo << endl;
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module