Check if a given number is a Perfect square using Binary Search | Java program to check if a given number is Perfect square using Binary Search ; Function to check for perfect square number ; Find the mid value from start and last ; Check if we got the number which is square root of the perfect square number N ; If the square ( mid ) is greater than N it means only lower values then mid will be possibly the square root of N ; If the square ( mid ) is less than N it means only higher values then mid will be possibly the square root of N ; Driver code
import java . util . * ; class GFG { static int checkPerfectSquare ( long N , long start , long last ) { long mid = ( start + last ) / 2 ; if ( start > last ) { return - 1 ; } if ( mid * mid == N ) { return ( int ) mid ; } else if ( mid * mid > N ) { return checkPerfectSquare ( N , start , mid - 1 ) ; } else { return checkPerfectSquare ( N , mid + 1 , last ) ; } } public static void main ( String [ ] args ) { long N = 65 ; System . out . println ( checkPerfectSquare ( N , 1 , N ) ) ; } }