## JavaScript – Cube Root & Beyond

Lately, I have been in a math oriented mood.  Yesterday, I was thinking about how the fact that you can take the square root of a number in JavaScript, but not the cube root, 4th root, etc..  Naturally, I looked to Wikipedia to find the algorithm to find the nth root of a number.  I developed the following unnecessary function:

```function bad_nthroot(x, n) {
// If an error occurs, don't return anything.
try {
// If an error occurs
// Loop through the nth root algorithm until no difference is found.
var x2, A = x, n1 = n - 1, itersLeft = 99;
do {
x2 = x;
x = (n1 * x2 + A / Math.pow(x2, n1)) / n;
} while(x != x2 && itersLeft--);

// If less than 100 iterations were done or if the difference between the
// previous approximation and the current one is acceptable, return the
// current one.
if((itersLeft || (Math.abs(x - x2) < 1 && (x < 0) == (x2 < 0))) && isFinite(x))
return x;
} catch(e){}
}
```

After testing out the function a bit and taking a look at an online example, I realized that I could have done it with the `Math.pow()`. After all, the cube root of a number is the same thing as that number to the power of 1/3. With this in mind, I redeveloped the function and came up with the following, more accurate function:

```function nthroot(x, n) {
try {
var negate = n % 2 == 1 && x < 0;
if(negate)
x = -x;
var possible = Math.pow(x, 1 / n);
n = Math.pow(possible, n);
if(Math.abs(x - n) < 1 && (x > 0 == n > 0))
return negate ? -possible : possible;
} catch(e){}
}
```

One notable difference is the fact that calling `bad_nthroot(8, 1/2)` results in 63.99999999999999. On the other hand, `nthroot(8, 1/2)` results in 64. There are many other differences as well.

The reason I created this function instead of using `Math.pow(x, 1 / n)` is because of examples such as `Math.pow(-8, 1 / 3)`. Even though the cube root of -8 is -2, `Math.pow(-8, 1 / 3)` results in NaN. On the other hand, `nthroot(-8, 3)` results in the expected value of `-2`.

If you find something wrong with my nthroot function, please let me know.

## Math In the Address Bar

Did you know that you can do math problems in the address bar of your browser? Regardless of what browser your using, you can use its address bar to find the answer to an arithmetic problem. For instance, let’s say that you are using Internet Explorer and all of a sudden someone asks you what 54 × 32 is. To figure it out, you type the following into the address bar and then hit the ENTER key:

```javascript:alert(54 * 32)
```

If you tried it out, you know the answer is 1728. What about the square root of 1728? To figure it out, you could use the following:

```javascript:alert(Math.sqrt(1728))
```

Now that you know that Math.sqrt(…) exists, you may be wondering, what other math related functions and constants like this exist. Here is a list of them derived from DevGuru.com:

Constants

Math.E
Euler’s constant and the base of natural logarithms (~2.7183).

Math.LN10
The natural log of 10.

Math.LN2
The natural log of 2.

Math.LOG10E
The base 10 log of E.

Math.LOG2E
The base 2 log of E.

Math.PI
PI – The circumference of a circle divided by its the diameter.

Math.SQRT1_2
One divided by the square root of 2.

Math.SQRT2
The square root of 2.

Functions

Math.abs(X)
The absolute value of the number X.

Math.acos(X)
The arccosine of X (which must be greater than or equal to -1 and less than or equal to 1) as a value between 0 and PI.

Math.asin(X)
The arcsine of X (which must be greater than or equal to -1 and less than or equal to 1) as a value between -PI / 2 and PI / 2.

Math.atan(X)
The arctangent of X as a value between -PI / 2 and PI / 2.

Math.atan2(X, Y)
The arctangent of X / Y as a value between -PI / 2 and PI / 2.

Math.ceil(X)
If X is an integer this evaluates to X, otherwise it evaluates to the next integer up.

Math.cos(X)
The cosine of X as a value between -1 and 1.

Math.exp(X)
The value of EX where E is Euler’s constant.

Math.floor(X)
If X is an integer, this evaluates to X, otherwise it evaluates to the next integer down.

Math.log(X)
The natural log (base E) of X (which must be greater than 0).

Math.max(X, Y, …)
The maximum number of X, Y, and any other parameters that you specify.

Math.min(X, Y, …)
The minimum number of X, Y, and any other parameters that you specify.

Math.pow(X, Y)
The value of XY.

Math.random()
A random number that is greater than or equal to 0 and less than 1.

Math.round(X)
The rounded value of X. If the fractional portion of the number is less than 0.5, the number is rounded down, otherwise it is rounded up.

Math.sin(X)
The sine of X as a value between -1 and 1.

Math.sqrt(X)
The square root X (which must be greater than or equal to 0).

Math.tan(X)
The tangent of X.

If you haven’t already guessed it, `alert(...)` actually displays whatever you specify in a new dialog box. Believe it or not, you can also assign values to variables and then use those variables later on. Of course, though, you have to do all of this on one line. Here is an example of what I mean by assigning values to variables and then using them later:

```javascript:age = 2011 - 1987; alert(age + Math.sqrt(age))
```

If you tried the above code out in your address bar, you now know what my age plus the square root of my age is.

All I have to say now is, “welcome to the world if JavaScript!!!”

## Power Set

As I was beefing up my past implementation of `cartesianProductOf()`, I decided to look into set theory a little bit more. After looking through some Wikipedia pages, I found another process that may be of interest to JavaScript programmers that have to deal with sets: a JavaScript implementation of finding a power set. Here is my code to do this:

```function powerSetOf(arrFull) {
var ret = [], fullLen = arrFull.length, last = fullLen - 1;
function get(arrPrefix, start, lenToFind) {
for(lenToFind--; start < fullLen; start++)
if(!lenToFind)
ret.push(arrPrefix.concat([arrFull[start]]));
else if(start < last)
get(arrPrefix.concat([arrFull[start]]), start + 1, lenToFind);
}
for(var lenToFind = fullLen; lenToFind > 0; lenToFind--)
get([], 0, lenToFind);
return ret.concat([[]]);
}
```

Although the above code works, I couldn’t help think that there was a simpler way of achieving the same goal. After fumbling around the idea in my head, I came up with the following, shorter solution:

```function powerSetOf(arr) {
var item, ret = [[]], max = arr.length - 1;
function fn(arrPrefix, start) {
for(; ret.push(item = arrPrefix.concat([arr[start]])) && start < max;)
fn(item, ++start);
}
if(max + 1)
fn([], 0);
return ret;
}
```

Unlike the first solution, the above one does not return the results ordered by size. On the other hand, this solution is shorter, an works faster.

You may have noticed that neither solution removes duplicates if they exist within the array. If you want to remove all duplicates from an array, you can make a build of jPaq that has the `Array.prototype.uniquify()` function and then use it as follows:

```// Your array of numbers or whatever.
var arr = [1,2,1,3,4,3,2];

// Get the power set for your array.
var arrPowerSet = powerSetOf(arr.uniquify());
```