Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Sunday, April 29, 2018

Square Root using Binary Search


Take start as 1 and end as number 

long floorSqrt(long x)
{
long res=-1;
if(x<=1)
return x;
long lo=1,high=x;
while(lo<=high)
{
    long mid=(lo+high)>>1;
    if(mid*mid==x)
    return mid;
     if(mid*mid<=x)
     {
         res=mid;
         lo=mid+1;
     }
     else
     high=mid-1;
}
return res;
}

0 Comments:

Post a Comment

Stats