Given a number N, Find the minimum number that needs to be added to or subtracted from N, to make it a perfect cube. If the number is to be added, print it with a + sign, else if the number is to be subtracted, print it with a – sign.
Examples:
Input: N = 25
Output: 2
Nearest perfect cube before 25 = 8
Nearest perfect cube after 25 = 27
Therefore 2 needs to be added to 25 to get the closest perfect cube
Input: N = 40
Output: -13
Nearest perfect cube before 40 = 25
Nearest perfect cube after 40 = 64
Therefore 13 needs to be subtracted from 40 to get the closest perfect cube
Approach:
- Get the number.
- Find the cube root of the number and convert the result as an integer.
- After converting the double value to integer, this will contain the root of the perfect cube before N, i.e. floor(cube root(N)).
- Then find the cube of this number, which will be the perfect cube before N.
- Find the root of the perfect cube after N, i.e. the ceil(cube root(N)).
- Then find the cube of this number, which will be the perfect cube after N.
- Check whether the cube of floor value is nearest to N or the ceil value.
- If the cube of floor value is nearest to N, print the difference with a -sign. Else print the difference between the cube of the ceil value and N with a + sign.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
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;
}
|
Java
class GFG {
static int nearest( int n)
{
int prevCube = ( int )Math.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;
}
public static void main (String[] args)
{
int n = 25 ;
System.out.println(nearest(n));
n = 27 ;
System.out.println(nearest(n)) ;
n = 40 ;
System.out.println(nearest(n)) ;
}
}
|