-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path14_SqareRootBinarysearch.cpp
74 lines (58 loc) · 1.28 KB
/
14_SqareRootBinarysearch.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <iostream>
using namespace std;
// this is brute force method for finding the square root of any number.
// int squareRoot(int n){
// int ans=0;
// int i=1;
// while (i*i<=n)
// {
// if(i*i<=n){
// ans=i;
// }
// i++;
// }
// return ans;
// }
long long int sqaureRoot(int n){
int s=0;
int e=n;
int ans=0;
long long int mid=s+(e-s)/2;
while (s<=e)
{
long long int sqaure=mid*mid;
if(sqaure==n){
return mid;
}
else if(sqaure<n){
ans=mid;
s=mid+1;
}
else{
e=mid-1;
}
mid=s+(e-s)/2;
}
return ans;
}
double morePrecision(int n, int precision, int tempSol){
double factor=1;
double ans=tempSol;
for(int i=0; i<precision; i++){
factor = factor/10;
for(double j=ans; j*j<n; j=j+factor){
ans=j;
}
}
return ans;
}
int main(){
int n;
cout<<"enter the value of the n:";
cin>>n;
// int ans=squareRoot(n);
// cout<<ans;
int tempSol=sqaureRoot(n);
cout<<"your ans is:"<<morePrecision(n,3,tempSol);
return 0;
}