Check if a number is perfect square without finding square root | C ++ program for above approach ; Program to find if x is a perfect square . ; Check if mid is perfect square ; Mid is small -> go right to increase mid ; Mid is large -> to left to decrease mid ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPerfectSquare ( int x ) { long long left = 1 , right = x ; while ( left <= right ) { long long mid = ( left + right ) / 2 ; if ( mid * mid == x ) { return true ; } if ( mid * mid < x ) { left = mid + 1 ; } else { right = mid - 1 ; } } return false ; } int main ( ) { int x = 2500 ; if ( isPerfectSquare ( x ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }