Skip to content

Instantly share code, notes, and snippets.

@dmnugent80
Last active August 29, 2015 14:13
Show Gist options
  • Save dmnugent80/062f5832d20d61b897f7 to your computer and use it in GitHub Desktop.
Save dmnugent80/062f5832d20d61b897f7 to your computer and use it in GitHub Desktop.
recursive pow function
public static int pow(int x, int n){
int mid;
int temp;
if (n == 0){
return 1;
}
if (n == 1){
return x;
}
mid = n / 2;
temp = pow(x, mid);
if (n%2 == 0){
return (temp * temp);
}
else{
return (x * temp * temp);
}
}
//alternate, works for negative numbers
public class Solution {
public double pow(double x, int n) {
if(n == 0)
return 1;
if(n == 1)
return x;
if(n%2 == 0)
return pow(x*x, n/2);
else{
if(n>0)
return x*pow(x*x, n/2);
else
return pow(x*x, n/2)/x;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment