text: Least number to be added to or subtracted from N to make it a Perfect Square | C ++ 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: #include <bits/stdc++.h> NEW_LINE using namespace std ; int nearest ( int n ) { int prevSquare = sqrt ( n ) ; int nextSquare = prevSquare + 1 ; prevSquare = prevSquare * prevSquare ; nextSquare = nextSquare * nextSquare ; int ans = ( n - prevSquare ) < ( nextSquare - n ) ? ( prevSquare - n ) : ( nextSquare - n ) ; return ans ; } int main ( ) { int n = 14 ; cout << nearest ( n ) << endl ; n = 16 ; cout << nearest ( n ) << endl ; n = 18 ; cout << nearest ( n ) << endl ; return 0 ; }