text: Least number to be added to or subtracted from N to make it a Perfect Square | 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: function nearest ( n ) { var prevSquare = parseInt ( Math . sqrt ( n ) ) ; var nextSquare = prevSquare + 1 ; prevSquare = prevSquare * prevSquare ; nextSquare = nextSquare * nextSquare ; if ( ( n - prevSquare ) < ( nextSquare - n ) ) { ans = parseInt ( ( prevSquare - n ) ) ; } else ans = parseInt ( ( nextSquare - n ) ) ; return ans ; } var n = 14 ; document . write ( nearest ( n ) + " " ) ; n = 16 ; document . write ( nearest ( n ) + " " ) ; n = 18 ; document . write ( nearest ( n ) + " " ) ;