-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary_Search.cpp
More file actions
71 lines (61 loc) · 1.79 KB
/
Binary_Search.cpp
File metadata and controls
71 lines (61 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <bits/stdc++.h>
using namespace std;
void solve() {
int n;
cin >> n;
// Highest x satisfy f(x), O(log(n))
auto binary_search1 = [](int low, int high, const function<bool(const int)>& f) -> int {
int lo = low - 1, hi = high + 1;
while (hi - lo > 1) {
int mid = lo + (hi - lo) / 2;
if (f(mid)) {
lo = mid;
} else {
hi = mid;
}
}
return lo;
};
// Lowest x satisfy f(x), O(log(n))
auto binary_search2 = [](int low, int high, const function<bool(const int)>& f) -> int {
int lo = low - 1, hi = high + 1;
while (hi - lo > 1) {
int mid = lo + (hi - lo) / 2;
if (f(mid)) {
hi = mid;
} else {
lo = mid;
}
}
return hi;
};
// Real value binary search, O(log(n / eps))
auto binary_search = [](double low, double high, const function<bool(const double)>& f) -> double {
const double eps = 1e-9;
double lo = low, hi = high;
while (hi - lo > eps) {
double mid = lo + (hi - lo) / 2;
if (f(mid)) {
lo = mid;
} else {
hi = mid;
}
}
return lo;
};
// Calculate floor sqrt & ceil sqrt
cout << binary_search1(0, n, [&n](int x) { return (int64_t)x * x <= n; }) << '\n';
cout << binary_search2(0, n, [&n](int x) { return (int64_t)x * x >= n; }) << '\n';
cout << fixed << setprecision(9);
cout << binary_search(0, n, [&n](double x) { return x * x <= n; }) << '\n';
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t = 1;
//cin >> t;
while (t--) {
solve();
}
return 0;
}