Created
July 10, 2018 21:02
-
-
Save kalyco/6c0a312f60a0784b8f2d05b0815471ed to your computer and use it in GitHub Desktop.
Write a recursive algorithm to perform x^n
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
// If exp is even, split in half twice and call each recursively | |
// otherwise, split in half twice and call each recursively AND multiply x | |
// Questions: | |
// What if exponent is 1? -- Then it will return x*1*1 | |
// What if exponent is 3+? -- If even, split. If odd, multiply next split value to x | |
int power(int base, int exponent) { | |
if (exponent == 0) return 1; | |
else if (exponent%2 == 0) // if even | |
return power(x, y/2)*power(x, y/2); | |
else { // if odd | |
return x*power(x, y/2)*power(x, y/2); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment