For what I know, the exponent in Javascript in only accessible throught the Math library with Math.pow.
Using exponent, cubic root of x
can be calculated by cubeRoot(x) = x^(1/3)
. In javascript using Math, this would look like var cubeRoot = Math.pow(x, 1/3)
.
Since your function has to return false if the result is fractional, I would make use of Math.round
to compare the cubic root. Your function would look like this:
function cubeRoot(x) {
var root = Math.pow(x, 1/3);
if (Math.round(root) !== root) {
return false;
}
return root;
}
However, since 1/3
is actcually 0.33333...
with a certain floating precision, this will not work for large cubes. For instance, Math.pow(45629414826904, 1/3)
might return you something like 35733.99999999998
.
What I would then do is if the difference with the rounded result is very small (say smaller than 1/1000000
), re-cube the number to see if this gets you back your original x
:
function cubeRoot(x) {
var root = Math.pow(x, 1/3);
var roundedRoot = Math.round(root);
var diff = Math.abs(root - roundedRoot);
if (diff <= 1/1000000) {
var reCubed = Math.pow(roundedRoot, 3);
if (reCubed === x) {
return roundedRoot;
}
return false;
}
if (diff !== roundedRoot) {
return false;
}
return root;
}
I tested a bit on y local Nodejs and it seems like it could handle cubes as large as 8000120000600001
(or 200001^3
) before failing to return false
on some non-cubes. Haven't tested it extensively, but this is the best hack I can come up with given the limitations of your problem.