Skip to content

Instantly share code, notes, and snippets.

@kalyco
Created July 10, 2018 21:02
Show Gist options
  • Save kalyco/6c0a312f60a0784b8f2d05b0815471ed to your computer and use it in GitHub Desktop.
Save kalyco/6c0a312f60a0784b8f2d05b0815471ed to your computer and use it in GitHub Desktop.
Write a recursive algorithm to perform x^n
// 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