Calculating nth power of x I have written this code which precisely calculates the nth power of x by a recursive method.

I compared my program with Java's pow(double, double) function, and most of the time I get comparable results, although sometimes pow is slow and the other times this program is slow.

Can anyone suggest any improvements or the way Java implements this function?

public double power(long x, int n) {

    double pow = 1L;
    if(n==0)
        return 1;
    if (n == 1)
        return x;
    if(n%2==0){
        pow = power(x, n / 2);
        return pow * pow;
    }
    else{
        pow = power(x,n/2);
        return pow * pow * x;
    }
}
The Java implementation of pow is implemented for double, rather than long, and probably uses logarithms. This makes direct comparison difficult - pow should have a more or less constant factor time, but double precision arithmetic can be expensive.

Otherwise, it seems reasonably straightforward.

If you're looking for speed, did you try using bit shifts rather than divides? It's possible that the compiler optimizes a divide by 2 to a bit shift, put possibly not. Though, the bit shift is probably somewhat less readable than the divide - and it is possible to be too clever.