如何最大程度地减少递归函数的调用时间

时间:2019-03-14 08:39:20

标签: c++

因此对于以下代码,我试图减少函数调用本身的时间,以使其更有效。该代码的目的是使用递归执行求幂。

int expo(const int m, const unsigned int n) 
{   
    funcCallCounter++;  //counts how many times the function is called
    if (n == 0)//base case
    {
        return 1;
    }

    else if (n % 2 == 0)// for even numbers
        return expo(m*m, n / 2);
    else
        return m * expo(m, n - 1);//for odd numbers
}

2 个答案:

答案 0 :(得分:3)

这是我最喜欢的递归博览会方法,它总是比您的方法更少调用

int expo(int a, int n) {

    funcCallCounter++;
    if (n == 0) {
        return 1;
    }
    int r = expo(a, n / 2);
    if (n % 2 == 0) {
       //Even n
        return r * r;
    }
    else {
        // Odd n    
        return a *r*r;

    }
}

答案 1 :(得分:0)

您可以使用班次来加快执行速度。

  • n % 2可以替换为n & 0x01
  • n / 2^k可以替换为n >> k

除法约为20个周期,而移位仅为1-2个周期。

但是,也许编译器自己看到了taht并且已经进行了优化。

最佳

相关问题