在 Java 中,你如何检查一个数字是否是一个立方体?
数字可以在范围之间−2,147,483,648..2,147,483,647
例如,给定以下数字,我们可以看到它们是立方体
8 (2^3) - True
27 (3^3) - True
64 (4^3) - True
(-1291)^3 和 1291^3 都已经超出了int
Java 的范围。所以无论如何有2581个这样的数字。老实说,查找表可能是最简单和最快的事情。
尝试一些Math
(java.lang.Math
):
boolean isCube(double input) {
double cubeRoot = Math.cbrt(input); // get the cube root
return Math.round(cubeRoot) == cubeRoot; // determine if number is integral
// Sorry for the stupid integrity determination. I tried to answer fast
// and really couldn't remember the better way to do that :)
}
尝试取立方根,将结果四舍五入并取其立方:
int a = (int) Math.round(Math.pow(number_to_test, 1.0/3.0));
return (number_to_test == a * a * a);
好吧,您可以执行以下操作(伪代码)
double x = number;
int b = floor (x ^ (1.0/3.0)) // ^ is exponentiation
if (b*b*b == number || (b+1)*(b+1)*(b+1) == number)
// it is a cube
添加一个循环:
int inputNum = //whatever ;
int counter = 1;
boolean po3 = false;
while(counter<inputNum || po3==true){
if((counter*counter*counter)==inputNum){
po3 = true;
} else {
counter++;
}
}