Results 1 to 5 of 5
Thread: Computing a cube (power of 3).
 01162009, 05:54 PM #1Member
 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.
 01162009, 06:02 PM #2Senior Member
 Join Date
 Jan 2009
 Posts
 119
 Rep Power
 0
I am guessing x * x * x would be faster, right?
 01162009, 06:50 PM #3Senior Member
 Join Date
 Nov 2008
 Posts
 286
 Rep Power
 8
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; ...
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)); }
Neil Coffey
Javamex  Java tutorials and performance info
 01162009, 08:07 PM #4Member
 Join Date
 Dec 2008
 Posts
 8
 Rep Power
 0
Thanks a lot! That helps me a lot.
Thank you.
 01162009, 10:13 PM #5Member
 Join Date
 Sep 2008
 Posts
 43
 Rep Power
 0
Similar Threads

Computing the sum
By Limuh in forum New To JavaReplies: 3Last Post: 08132008, 06:00 AM 
Rubiks Cube Solver
By sufs2000 in forum Advanced JavaReplies: 0Last Post: 06032008, 03:20 PM 
distributed computing in java
By pushpik in forum Advanced JavaReplies: 0Last Post: 03312008, 06:50 PM 
Computing Fibonacci numbers recursively
By Java Tip in forum Java TipReplies: 0Last Post: 01222008, 09:20 PM
Bookmarks