Check if a given number is a Perfect square using Binary Search | C ++ 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
#include <iostream> NEW_LINE using namespace std ; int checkPerfectSquare ( long int N , long int start , long int last ) { long int mid = ( start + last ) / 2 ; if ( start > last ) { return -1 ; } if ( mid * mid == N ) { return mid ; } else if ( mid * mid > N ) { return checkPerfectSquare ( N , start , mid - 1 ) ; } else { return checkPerfectSquare ( N , mid + 1 , last ) ; } } int main ( ) { long int N = 65 ; cout << checkPerfectSquare ( N , 1 , N ) ; return 0 ; }