text: Least number to be added to or subtracted from N to make it a Perfect Cube | C ++ implementation of the approach ; Function to return the Least number ; Get the perfect cube 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 prevCube = cbrt ( n ) ; int nextCube = prevCube + 1 ; prevCube = prevCube * prevCube * prevCube ; nextCube = nextCube * nextCube * nextCube ; int ans = ( n - prevCube ) < ( nextCube - n ) ? ( prevCube - n ) : ( nextCube - n ) ; return ans ; } int main ( ) { int n = 25 ; cout << nearest ( n ) << endl ; n = 27 ; cout << nearest ( n ) << endl ; n = 40 ; cout << nearest ( n ) << endl ; return 0 ; }