Reputation:
In Java how do you check if a number is a cube ?
The number can be between the range −2,147,483,648..2,147,483,647
Say for instance given the following numbers we can see that they are cubes
8 (2^3) - True
27 (3^3) - True
64 (4^3) - True
Upvotes: 1
Views: 5738
Reputation: 66886
(-1291)^3 and 1291^3 are both already outside the range of an int
in Java. So there are 2581 such numbers anyway. Honestly a lookup table might be the easiest and fastest thing.
Upvotes: 5
Reputation:
Try some 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 :)
}
Upvotes: 2
Reputation: 540
Try to take a cubic root, round the result and take its cube:
int a = (int) Math.round(Math.pow(number_to_test, 1.0/3.0));
return (number_to_test == a * a * a);
Upvotes: 2
Reputation: 36349
Well, you could do the following (pseudocode)
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
Upvotes: 1
Reputation: 194
Add a loop:
int inputNum = //whatever ;
int counter = 1;
boolean po3 = false;
while(counter<inputNum || po3==true){
if((counter*counter*counter)==inputNum){
po3 = true;
} else {
counter++;
}
}
Upvotes: -2