-
Notifications
You must be signed in to change notification settings - Fork 44
/
Square root.cpp
52 lines (43 loc) · 1.04 KB
/
Square root.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
// In this program I will write the code of how to find Square Root of a Number using Binary Search
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int main()
{
cout<<"Enter number whose square root has to be found: ";
int n;
cin>>n;
if(n == 1)
{
cout<<"Square root is 1 ";
}
else
{
// binary search to reduce time complexity...
int l = 0, r = n-1;
int ans ;
int m = (l+r)/2;
while(l<=r)
{
// int i = 0;
if(m*m == n)
{
ans = m;
break;
}
else if(m*m < n)
{
l = m + 1;
ans = m;
}
else
{
r = m - 1;
}
m = (r+l)/2;
// cout<<"Square root is "<<i;
}
cout<<"The approx answer of entered number is "<<ans;
}
return 0;
}