forked from piyush01123/Daily-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsol.cpp
45 lines (36 loc) · 921 Bytes
/
sol.cpp
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
#include <iostream>
#define TOL 0.001
bool isNearlyEqual(double a, double b){
// checks if a and b are equal with tolerance value TOL
double diff = a-b;
diff = (diff>=0)?diff:-diff;
return diff<=TOL;
}
double squareRoot(double n){
// employs binary search to find square root of a number correct within tolerance
double lower = 0;
double higher = n;
double n_sqrt = (lower+higher)/2;
while (!isNearlyEqual(n_sqrt*n_sqrt, n)) {
if (n_sqrt*n_sqrt>n) {
higher = n_sqrt;
} else {
lower = n_sqrt;
}
n_sqrt = (lower+higher)/2;
}
return n_sqrt;
}
void test(){
// builds and runs test cases
std::cout << squareRoot(9) << std::endl;
std::cout << squareRoot(89.121) << std::endl;
std::cout << squareRoot(49) << std::endl;
std::cout << squareRoot(0) << std::endl;
std::cout << squareRoot(1) << std::endl;
}
int main(){
// run the test
test();
return 0;
}