For a whole number n, find the largest whole number r with r × r at most n.
What to build
Binary search r between 0 and 2,000,000,000. If mid × mid is at most n, mid works and a larger one might too, so move lo up; otherwise move hi down.
Requirements
- Use binary search on the answer, not a loop from 0
- Use
long longso thatmid × middoes not overflow - Answer several numbers, one per line
Input
The first line has t. Each of the next t lines has one number n.
Output
For each n, the largest r with r × r ≤ n, one per line.
Constraints
1 ≤ t ≤ 1,000. 0 ≤ n ≤ 10¹⁸.
Example
Input:
4
0
15
16
17
Output:
0
3
4
4
Why it works
The values r with r × r ≤ n form a range that starts at 0, so the largest of them is the edge that binary search finds in about 31 checks. Since n ≤ 10¹⁸, the root is at most 10⁹ and mid × mid stays below 4 × 10¹⁸, which fits in long long.
Examples
4 0 15 16 17
0 3 4 4
2 1 1000000000000000000
1 1000000000
Hints
Hint 1
lo = 0, hi = 2000000000. Use mid = lo + (hi - lo + 1) / 2 so the loop makes progress.
Hint 2
If mid * mid <= n then lo = mid, else hi = mid - 1.
Hint 3
Loop while lo < hi; the answer is lo.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
long long n;
cin >> n;
long long lo = 0, hi = 2000000000;
while (lo < hi) {
long long mid = lo + (hi - lo + 1) / 2;
if (mid * mid <= n) lo = mid;
else hi = mid - 1;
}
cout << lo << "\n";
}
return 0;
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step