Last active
August 29, 2015 14:13
-
-
Save dmnugent80/062f5832d20d61b897f7 to your computer and use it in GitHub Desktop.
recursive pow function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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