-
Notifications
You must be signed in to change notification settings - Fork 0
/
61-binary-sqrt.cpp
50 lines (47 loc) · 1.06 KB
/
61-binary-sqrt.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
46
47
48
49
50
#include <iostream>
#include <vector>
using namespace std;
double mySqrt(int x, int prec) {
int l=0, r=x;
long long int m= l + (r-l)/2, intAns=m;
while(l<=r){
m= l+ (r-l)/2;
if (m*m == x){
intAns = m;
break;
}
if(m*m > x){
r = m-1;
}
if(m*m < x){
l = m+1;
intAns = m;
}
}
double ans = (double)intAns;
double mul = 1;
for (int i=0; i< prec; i++){
cout << "precesion iteration: " << i << endl;
mul /= 10;
for (int j=0; j<10; j++){
double can = ans + mul;
cout <<"can: "<<can << " | can*can: " << can*can << endl;
if (can*can == (double)x){
return can;
}
else if (can*can < (double)x) ans = can;
else if (can*can > (double)x){
cout << "breaking the loop \n";
break;
}
}
}
return ans;
}
int main() {
double testD = 1.41421;
cout << mySqrt(2,10) << endl;
double bl = testD*testD;
cout << bl << endl;
return 0;
}