Square root binary search

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;

}

instead of float use double
because if you want more precision(>2) then you need more memory
double is 8 byte and float is 4 bytes hence use double

Modified Code

yes, its working but float has 6-7 significant digits it should have handled it but it is not

it will fail as ans*ans exceed 6-7 significant digits

1 Like

i hope your doubt resolved now
so please mark it as resolved from your side