I simply want to write some code that makes use of recursion of functions to raise a base to its power. I know that recursion is not the most right way to do things in C++,
Here's a version with better complexity (O(lg exponent)
, instead of O(exponent)
), which is conceptually similar to leftroundabout's version.
int raisingTo(int base const, unsigned int const exponent, int scalar = 1)
{
if (exponent == 0)
return scalar;
if (exponent & 1) scalar *= base;
return raisingTo(base * base, exponent >> 1, scalar);
}
It also uses tail recursion, which generally leads to better optimized machine code.