patternjavaMinor
Calculating nth power of x
Viewed 0 times
nthcalculatingpower
Problem
I have written this code which precisely calculates the nth power of x by a recursive method.
I compared my program with Java's
Can anyone suggest any improvements or the way Java implements this function?
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;
}
}Solution
The Java implementation of
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.
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.
Context
StackExchange Code Review Q#11762, answer score: 6
Revisions (0)
No revisions yet.