-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqrt_scratch.cpp
More file actions
49 lines (41 loc) · 819 Bytes
/
sqrt_scratch.cpp
File metadata and controls
49 lines (41 loc) · 819 Bytes
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
#include<iostream>
#include<cmath>
using namespace std;
/*
* sqrt_: Takes a float number and returns its
* square root without using built in function
* sqrt()
*
* returns: square root of number is possible
* else returns -1.0.
*/
float sqrt_(float num){
float low = 1, high = num, mid;
while(low <= high){
mid = (low+high)/2;
float sq = mid * mid;
if(abs(num - sq) < 0.00001)
return mid;
else if (num - sq > 0)
low = mid;
else
high = mid;
}
return -1.0;
}
int main(){
float num, res;
//Take input
cout<<"\n Enter number to find Square root: ";
cin>>num;
// Find Square Root
res = sqrt_(num);
// Display N/A if the root is not applicable
// Else print result
if(res < 0){
cout<<"\n N/A";
}else{
cout<<"\n The square root of "<<num<<" is: "<<res;
}
return 0;
}