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
< ? php function isPerfect ( $ N ) { if ( ( sqrt ( $ N ) - floor ( sqrt ( $ N ) ) ) != 0 ) return false ; return true ; } function getClosestPerfectSquare ( $ N ) { if ( isPerfect ( $ N ) ) { echo $ N , " ▁ " , "0" , " STRNEWLINE " ; return ; } $ aboveN = -1 ; $ belowN = -1 ; $ 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 -- ; } $ diff1 = $ aboveN - $ N ; $ diff2 = $ N - $ belowN ; if ( $ diff1 > $ diff2 ) echo $ belowN , " ▁ " , $ diff2 ; else echo $ aboveN , " ▁ " , $ diff1 ; } $ N = 1500 ; getClosestPerfectSquare ( $ N ) ; ? >