Closest perfect square and its distance | 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
function isPerfect ( N ) { if ( ( Math . sqrt ( N ) - Math . floor ( Math . sqrt ( N ) ) ) != 0 ) return false ; return true ; } function getClosestPerfectSquare ( N ) { if ( isPerfect ( N ) ) { document . write ( N + " " + " " + " " ) ; return ; } let aboveN = - 1 , belowN = - 1 ; let 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 -- ; } let diff1 = aboveN - N ; let diff2 = N - belowN ; if ( diff1 > diff2 ) document . write ( belowN + " " + diff2 ) ; else document . write ( aboveN + " " + diff1 ) ; } let N = 1500 ; getClosestPerfectSquare ( N ) ;