Least number to be added to or subtracted from N to make it a Perfect Square | Java 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
class GFG { static int nearest ( int n ) { int prevSquare = ( int ) Math . sqrt ( n ) ; int nextSquare = prevSquare + 1 ; prevSquare = prevSquare * prevSquare ; nextSquare = nextSquare * nextSquare ; int ans = ( n - prevSquare ) < ( nextSquare - n ) ? ( prevSquare - n ) : ( nextSquare - n ) ; return ans ; } public static void main ( String [ ] args ) { int n = 14 ; System . out . println ( nearest ( n ) ) ; n = 16 ; System . out . println ( nearest ( n ) ) ; n = 18 ; System . out . println ( nearest ( n ) ) ; } }