Closest perfect square and its distance | C # 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
using System ; class GFG { static bool isPerfect ( int N ) { if ( ( Math . Sqrt ( N ) - Math . Floor ( Math . Sqrt ( N ) ) ) != 0 ) return false ; return true ; } static void getClosestPerfectSquare ( int N ) { if ( isPerfect ( N ) ) { Console . WriteLine ( N + " ▁ " + "0" ) ; 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 ) Console . WriteLine ( belowN + " ▁ " + diff2 ) ; else Console . WriteLine ( aboveN + " ▁ " + diff1 ) ; } public static void Main ( ) { int N = 1500 ; getClosestPerfectSquare ( N ) ; } }