0
long long int floorSqrt(long long int x) 
{
    // Your code goes here   
    long long int l=0 , r = x, ans;
    while(l<=r){
        long long int mid= (int)(l+r)/2;
        long long int m = mid*mid;
        if( m == x){
            return mid;
        }
        if(mid>= (int)x/mid){
            r = mid -1;
        }
        if( mid <=(int)x/mid){
            l = mid+1;
            ans = mid;
        }
    }
    return ans;
}

this is the function made to calculate the square root of a given number X , using binary search to complete it in o(log n) i am using GFG code compiler , using a gcc5.4

  • If x is 0, mid will be zero, so you'll get a divide by zero exception. Is that what you were seeing? – Mark Lavin Aug 13 '21 at 18:51
  • 4
    More accurate, `x < 2` ever being true going into this function will cause a div-0. Integer division of of either 1/2 or 0/2 is 0 in either case. Somewhat related, what are you hoping to *gain* by that cast to `(int)` for the division in the initial calculation of `mid` anyway? As near as I can see that is completely pointless. – WhozCraig Aug 13 '21 at 18:53
  • 1
    Some tangentially related side-reading:[Why does integer division by zero result in a floating point exception?](https://stackoverflow.com/questions/16928942) – user4581301 Aug 13 '21 at 18:58
  • "Floating-point exception" is an unfortunate misnomer. It should be called "numeric exception", at least in any system where some errors in pure integer arithmetic generate the exception. – Kaz Aug 13 '21 at 19:06

1 Answers1

0

You could try changing the function:

long long int floorSqrt(long long int x) 
{
    // This will make sqrt(1) = 1, sqrt(0) = 0
    if (x < 2) {
        return x;
    }
    ...

so that any x values that would cause mid to ever equal 0 will be handled. Alternatively you could check for mid == 0 inside the while loop before dividing by it.

mattlangford
  • 1,260
  • 1
  • 8
  • 12