# Thread: Computing a cube (power of 3).

1. Member
Join Date
Dec 2008
Posts
8
Rep Power
0

## 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.

2. Senior Member
Join Date
Jan 2009
Posts
119
Rep Power
0
I am guessing x * x * x would be faster, right?

3. Senior Member
Join Date
Nov 2008
Posts
286
Rep Power
9
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:

Java 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:

Java 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).

4. Member
Join Date
Dec 2008
Posts
8
Rep Power
0
Thanks a lot! That helps me a lot.

Thank you.

5. Member
Join Date
Sep 2008
Posts
43
Rep Power
0
hat off to you neil coffey. That was the perfect answer for another question I had! ;)

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•