Square root of an integer | A Java program to find floor ( sqrt ( 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 ) ; else If mid * mid is greater than x ; Driver Method
public class Test { public static int floorSqrt ( int x ) { if ( x == 0 x == 1 ) return x ; long start = 1 , end = x , ans = 0 ; while ( start <= end ) { int mid = ( start + end ) / 2 ; if ( mid * mid == x ) return ( int ) mid ; if ( mid * mid < x ) { start = mid + 1 ; ans = mid ; } end = mid - 1 ; } return ( int ) ans ; } public static void main ( String args [ ] ) { int x = 11 ; System . out . println ( floorSqrt ( x ) ) ; } }