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
from math import sqrt , floor NEW_LINE def isPerfect ( N ) : NEW_LINE INDENT if ( sqrt ( N ) - floor ( sqrt ( N ) ) != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT def getClosestPerfectSquare ( N ) : NEW_LINE INDENT if ( isPerfect ( N ) ) : NEW_LINE INDENT print ( N , "0" ) NEW_LINE return NEW_LINE DEDENT aboveN = - 1 NEW_LINE belowN = - 1 NEW_LINE n1 = 0 NEW_LINE n1 = N + 1 NEW_LINE while ( True ) : NEW_LINE INDENT if ( isPerfect ( n1 ) ) : NEW_LINE INDENT aboveN = n1 NEW_LINE break NEW_LINE DEDENT else : NEW_LINE INDENT n1 += 1 NEW_LINE DEDENT DEDENT n1 = N - 1 NEW_LINE while ( True ) : NEW_LINE INDENT if ( isPerfect ( n1 ) ) : NEW_LINE INDENT belowN = n1 NEW_LINE break NEW_LINE DEDENT else : NEW_LINE INDENT n1 -= 1 NEW_LINE DEDENT DEDENT diff1 = aboveN - N NEW_LINE diff2 = N - belowN NEW_LINE if ( diff1 > diff2 ) : NEW_LINE INDENT print ( belowN , diff2 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( aboveN , diff1 ) NEW_LINE DEDENT DEDENT N = 1500 NEW_LINE getClosestPerfectSquare ( N ) NEW_LINE