I copied the same code which is taught in the square root by binary search video but I am getting wrong result in one test case inputting 77 and 3. please check.
#include
using namespace std;
float root_finder(int n, int p)
{
int s = 0;
int e = n;
float ans = -1;
while (s <= e)
{
int mid = (s + e) >> 1; //left shift by 1 equals to /2
if (mid * mid == n)
{
return mid;
}
else if (mid * mid < n)
{
ans = mid;
s = mid + 1;
}
else if (mid * mid > n)
{
e = mid - 1;
}
}
float increment=0.1;
for(int times=0;times<p;times++)
{
while(ans*ans<=n)
{
ans=ans+increment;
}
ans=ans-increment;
increment=increment/10;
}
return ans;
}
int main()
{
int n;
cout << "enter the number\n";
cin >> n;
int p;
cout << "enter precision\n";
cin >> p;
cout << root_finder(n, p);
return 0;
}