给定数字N ,找到需要添加到N或从N减去的最小数字,以使其成为理想的立方体。如果要加数字,则用+号打印;否则,如果要减数字,则用-号打印。
例子:
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
方法:
- 获取号码。
- 查找数字的立方根,并将结果转换为整数。
- 将double值转换为整数后,它将包含N之前的完美立方体的根,即floor(cube root(N)) 。
- 然后找到该数字的立方体,它将是N之前的完美立方体。
- 在N之后找到理想立方的根,即ceil(cube root(N)) 。
- 然后找到该数字的立方体,它将是N之后的完美立方体。
- 检查底值立方是否最接近N或ceil值。
- 如果底值的立方最接近N,则用-符号打印差异。否则,打印出ceil值的多维数据集和带有+号的N之间的差。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the Least number
int nearest(int n)
{
// Get the perfect cube
// before and after N
int prevCube = cbrt(n);
int nextCube = prevCube + 1;
prevCube = prevCube * prevCube * prevCube;
nextCube = nextCube * nextCube * nextCube;
// Check which is nearest to N
int ans
= (n - prevCube) < (nextCube - n)
? (prevCube - n)
: (nextCube - n);
// return the result
return ans;
}
// Driver code
int main()
{
int n = 25;
cout << nearest(n) << endl;
n = 27;
cout << nearest(n) << endl;
n = 40;
cout << nearest(n) << endl;
return 0;
}
Java
// Java implementation of the approach
class GFG {
// Function to return the Least number
static int nearest(int n)
{
// Get the perfect cube
// before and after N
int prevCube = (int)Math.cbrt(n);
int nextCube = prevCube + 1;
prevCube = prevCube * prevCube * prevCube;
nextCube = nextCube * nextCube * nextCube;
// Check which is nearest to N
int ans = (n - prevCube) < (nextCube - n) ?
(prevCube - n) : (nextCube - n);
// return the result
return ans;
}
// Driver code
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)) ;
}
}
// This code is contributed by Yash_R
输出:
2
0
-13