Results 1 to 5 of 5
  1. #1
    Jary316 is offline Member
    Join Date
    Dec 2008
    Posts
    8
    Rep Power
    0

    Default 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. #2
    MuslimCoder is offline Senior Member
    Join Date
    Jan 2009
    Posts
    119
    Rep Power
    0

    Default

    I am guessing x * x * x would be faster, right?

  3. #3
    neilcoffey is offline Senior Member
    Join Date
    Nov 2008
    Posts
    286
    Rep Power
    6

    Default

    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. #4
    Jary316 is offline Member
    Join Date
    Dec 2008
    Posts
    8
    Rep Power
    0

    Default

    Thanks a lot! That helps me a lot.

    Thank you.

  5. #5
    2potatocakes is offline Member
    Join Date
    Sep 2008
    Posts
    43
    Rep Power
    0

    Default

    hat off to you neil coffey. That was the perfect answer for another question I had! ;)

Similar Threads

  1. Computing the sum
    By Limuh in forum New To Java
    Replies: 3
    Last Post: 08-13-2008, 06:00 AM
  2. Rubiks Cube Solver
    By sufs2000 in forum Advanced Java
    Replies: 0
    Last Post: 06-03-2008, 03:20 PM
  3. distributed computing in java
    By pushpik in forum Advanced Java
    Replies: 0
    Last Post: 03-31-2008, 06:50 PM
  4. Computing Fibonacci numbers recursively
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 01-22-2008, 08:20 PM

Posting Permissions

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