text: Least number to be added to or subtracted from N to make it a Perfect Square | Python3 implementation of the approach ; Function to return the Least number ; Get the perfect square before and after N ; Check which is nearest to N ; return the result ; Driver code
code: from math import sqrt NEW_LINE def nearest ( n ) : NEW_LINE INDENT prevSquare = int ( sqrt ( n ) ) ; NEW_LINE nextSquare = prevSquare + 1 ; NEW_LINE prevSquare = prevSquare * prevSquare ; NEW_LINE nextSquare = nextSquare * nextSquare ; NEW_LINE ans = ( prevSquare - n ) if ( n - prevSquare ) < ( nextSquare - n ) else ( nextSquare - n ) ; NEW_LINE return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 14 ; NEW_LINE print ( nearest ( n ) ) ; NEW_LINE n = 16 ; NEW_LINE print ( nearest ( n ) ) ; NEW_LINE n = 18 ; NEW_LINE print ( nearest ( n ) ) ; NEW_LINE DEDENT