1

I'd like to change this exponentiation method (n is the exponent):

public static double exponentiate(double x, int n) {
    counter++; 
    if (n == 0) {
        return 1.0;
    } else if (n == 1) {
        return x;
    } else {
        return x * exponentiate(x, n - 1);
    }
}

I'd like to change the method to make it more efficient, so the method is not opened n times but maximum (n/2+1) times WITHOUT using the class MATH.

So far I came up with this code:

public static double exponentiate(double x, int n) {
    counter++; 
    if (n == 0) {
        return 1.0;
    } else if (n == 1) {
        return x;
    } else {
        if (n % 2 == 0) {
            n = n-(n-1);
        } else {
            n = ((n-1) / 2) + n;
        }
        return ((x * x) * exponentiate(x, n - (n / 2)));
    }
}

But somehow it only works for odd n, not vor even n.

Can somebody help?

Thanks!

2 Answers2

0

I don't know if this is the solution you search but this is an example of an algorithm that perform exponentiation in O(log(n)) time

public static double exponentiate(double x, int n) {
    if (n == 0) {
        return 1.0;
    } else if (n == 1) {
        return x;
    } else {
        return ((n % 2 == 0) ? 1 : x) * exponentiate(x * x, n  / 2);
    }
}
b.GHILAS
  • 2,273
  • 1
  • 8
  • 16
0

I think you can optimize the above method to run for O(logn) by calculating exponentiate(x,n/2) once and using it.

Something like this:-

public static double exponentiate(double x, int n) 
{ 
    int temp; 
    if(n == 0) 
        return 1; 
    temp = exponentiate(x, n/2); 
    if (n%2 == 0) 
        return temp*temp; 
    else
        return x*temp*temp; 
} 

Hope this helps!

zenwraight
  • 2,002
  • 1
  • 10
  • 14