Using Recursion to raise a base to its exponent - C++

后端 未结 5 670
不知归路
不知归路 2020-12-22 10:42

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++,

5条回答
  •  轮回少年
    2020-12-22 11:13

    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.

提交回复
热议问题