# Computing a cube (power of 3).

• 01-16-2009, 05:54 PM
Jary316
Computing a cube (power of 3).
Hello everyone,

I am trying to compute the cube of a bunch of integers, starting from 1 to n.

I am dealing with efficiency and I want to know the fastest way to compute those numbers.

I am currently using x * x * x, rather than Math.pow(x, 3).
I would like to know if my actual solution is the fastest, and if there is any that would be better.

Thank you very much.
• 01-16-2009, 06:02 PM
MuslimCoder
I am guessing x * x * x would be faster, right?
• 01-16-2009, 06:50 PM
neilcoffey
If speed is important, always calculate integer powers with combinations of multiplying the current result by itself or by the original number. So extending the logic:

Code:

```x^4 : y = x * x; return y * y; x^5 : y = x * x; return y * y * x; x^6 : y = x * x * x; return y * y; ...```
Not only is it faster, but it turns out to be quite a lot faster. On my Pentium, each multiplication requires 2 clock cycles, but Math.pow() requires up to around 700 clock cycles!

So in general, Math.pow() is an extremely slow way of calculating a power if the exponent is known in advance. (And even for an arbitrary integer exponent, there are still faster ways of doing it.)

Also, on my Pentium, the following:

Code:

```public double power(double x, double y) {   return Math.exp(y * Math.log(x)); }```
is about twice as fast as Math.pow(x, y) and will return virtually the same result (I think there would be cases where the least significant digit is not as accurate, but that rarely matters).
• 01-16-2009, 08:07 PM
Jary316
Thanks a lot! That helps me a lot.

Thank you.
• 01-16-2009, 10:13 PM
2potatocakes
hat off to you neil coffey. That was the perfect answer for another question I had! ;)