forked from shivprime94/Data-Structure-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SquareRoot.cpp
56 lines (48 loc) · 1.12 KB
/
SquareRoot.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
// program to find the square root of any number upto 5 decimal place
#include<iostream>
using namespace std;
// funtion to find square root of number n
double sqrt(int n,int p){
int s = 0; // s = start
int e = n; // e = end
double root = 0.0;
int x=0;
// binarysearch to find the the perfect square root
while(s<=e){
int mid=s+(e-s)/2;
if(mid*mid == n){
return mid;
}
if(mid*mid > n){
e=mid-1;
}else{
s=mid+1;
}
x = mid;
}
root = x-1;
int k=1;
// precision
double incr = 0.0;
for(int i=0; i<p; i++){
while(root*root <= n){
incr += 0.1/k;
root += incr;
}
root -= incr;
incr /= 10;
k=k*10;
incr = 0.1/k;
}
return root;
}
int main(){
int n;
cout<<"enter number :" ;
cin>>n;
int p; //precision value (upto 5 decimal place value)
cout<<"enter precision value :";
cin>>p;
cout<<sqrt(n,p)<<endl;
return 0;
}