Square root of an integer | Returns floor of square root of x ; Base cases ; Do Binary Search for floor ( sqrt ( x ) ) ; If x is a perfect square ; Since we need floor , we update answer when mid * mid is smaller than x , and move closer to sqrt ( x ) ; If mid * mid is greater than x ; driver code
def floorSqrt ( x ) : NEW_LINE INDENT if ( x == 0 or x == 1 ) : NEW_LINE INDENT return x NEW_LINE DEDENT start = 1 NEW_LINE end = x NEW_LINE while ( start <= end ) : NEW_LINE INDENT mid = ( start + end ) // 2 NEW_LINE if ( mid * mid == x ) : NEW_LINE INDENT return mid NEW_LINE DEDENT if ( mid * mid < x ) : NEW_LINE INDENT start = mid + 1 NEW_LINE ans = mid NEW_LINE DEDENT else : NEW_LINE INDENT end = mid - 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT x = 11 NEW_LINE print ( floorSqrt ( x ) ) NEW_LINE