Search code examples
javarecursionmethodsexponentiationcoding-efficiency

Java recursion exponentiation method making recursion more efficient


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!


Solution

  • 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!