在Java中,如何检查数字是否是多维数据集?
该数字可以在−2,147,483,648..2,147,483,647
比如说如果给出以下数字,我们可以看到它们是立方体
8 (2^3) - True
27 (3^3) - True
64 (4^3) - True
答案 0 :(得分:5)
( - 1291)^ 3和1291 ^ 3都已经在Java中int
的范围之外。所以无论如何都有2581这样的数字。老实说,查找表可能是最容易和最快的事情。
答案 1 :(得分:2)
尝试一些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 :)
}
答案 2 :(得分:2)
尝试取一个立方根,对结果进行舍入并取其立方体:
int a = (int) Math.round(Math.pow(number_to_test, 1.0/3.0));
return (number_to_test == a * a * a);
答案 3 :(得分:1)
好吧,你可以做以下(伪代码)
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
答案 4 :(得分:-2)
添加循环:
int inputNum = //whatever ;
int counter = 1;
boolean po3 = false;
while(counter<inputNum || po3==true){
if((counter*counter*counter)==inputNum){
po3 = true;
} else {
counter++;
}
}