Closest perfect square and its distance | CPP program to find the closest perfect square taking minimum steps to reach from a number ; Function to check if a number is perfect square or not ; Function to find the closest perfect square taking minimum steps to reach from a number ; Variables to store first perfect square number above and below N ; Finding first perfect square number greater than N ; Finding first perfect square number less than N ; Variables to store the differences ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPerfect ( int N ) { if ( ( sqrt ( N ) - floor ( sqrt ( N ) ) ) != 0 ) return false ; return true ; } void getClosestPerfectSquare ( int N ) { if ( isPerfect ( N ) ) { cout << N << " ▁ " << "0" << endl ; return ; } int aboveN = -1 , belowN = -1 ; int n1 ; n1 = N + 1 ; while ( true ) { if ( isPerfect ( n1 ) ) { aboveN = n1 ; break ; } else n1 ++ ; } n1 = N - 1 ; while ( true ) { if ( isPerfect ( n1 ) ) { belowN = n1 ; break ; } else n1 -- ; } int diff1 = aboveN - N ; int diff2 = N - belowN ; if ( diff1 > diff2 ) cout << belowN << " ▁ " << diff2 ; else cout << aboveN << " ▁ " << diff1 ; } int main ( ) { int N = 1500 ; getClosestPerfectSquare ( N ) ; }