如何计算递归的次数? (计算x ^ n的乘法次数)

时间:2018-02-28 01:14:33

标签: c++ c++11

我在查找如何增加计数(我的代码中的多数)方面遇到了一些麻烦,因为power2的计数器等同于power1的计数器。我的程序以不同的方式比较计算x ^ n的效率。我已经查找了如何计算递归调用自身的次数的解决方案,但无论我实现什么方法,我得到的输出都不正确。任何帮助或指导将不胜感激!

到目前为止,这是我的代码的一部分(power1有正确的计数器):

template <class T>
T power1(T x, unsigned int n, unsigned int& mults)
{
mults = 0;

if (n == 0)
    return 1;
else if (n == 1)
    return x;
else
{
    T total = 1;

    for (int i = 0; i < n; ++i)
    {
        total = total * x;
        ++mults;
    }
    mults -= 1;

    return total;
}
}


template <class T>
T power2(T x, unsigned int n, unsigned int& mults)
{
++mults;

if (n == 0)
{
    mults = 0;
    return 1;
}
else if (n == 1)
    return x;
else
{
    if (n > 1)
    {
        return (x * power2(x, n - 1, mults));
    }
}

return x;
}

这是我输出的一部分:

Test for integer base:
2^0 = 1: mults1 = 0, mults2 = 0
2^1 = 2: mults1 = 0, mults2 = 1
2^2 = 4: mults1 = 1, mults2 = 3
2^3 = 8: mults1 = 2, mults2 = 6
2^4 = 16: mults1 = 3, mults2 = 10
2^5 = 32: mults1 = 4, mults2 = 15
2^6 = 64: mults1 = 5, mults2 = 21
2^7 = 128: mults1 = 6, mults2 = 28
2^8 = 256: mults1 = 7, mults2 = 36
2^9 = 512: mults1 = 8, mults2 = 45

2 个答案:

答案 0 :(得分:3)

您需要在两次通话之间重置mults2。

简单的解决方案是

power2(2,2,foo);

//reset before next call
foo=0;
power2(2,3,foo);

或者您可以让该功能自动重置。

template <class T>
T power2(T x, unsigned int n, unsigned int& mults, bool init = true)
{
    if (init)
        mults=0;

    if (n == 0)
    {
        mults = 0;
        return 1;
    }
    else if (n == 1)
        return x;
    else
    {
        if (n > 1)
        {
            ++mults;
            return (x * power2(x, n - 1, mults, false));
        }
    }

    return x;
}

答案 1 :(得分:1)

我认为这里有两个问题:你没有在每次调用power2之前重置mults,并且你在开始时递增。这给出了正确的结果:

#include <iostream>
using namespace std;

template <class T>
T power2(T x, unsigned int n, unsigned int& mults)
{
    if (n == 0)
    {
        mults = 0;
        return 1;
    }
    else if (n == 1)
        return x;
    else
    {
        if (n > 1)
        {
            return (x * power2(x, n - 1, ++mults));
        }
    }
}

int main() {
    int x = 2;
    int n = 4;
    unsigned int mults = 0;
    int res = power2(x, n, mults);
    std::cout << x << "^" << n << " = " << res << " - mults: " << mults << "\n";

    x = 2;
    n = 5;
    mults = 0;
    res = power2(2, 5, mults);

    std::cout << x << "^" << n << " = " << res << " - mults: " << mults << "\n";

    return 0;
}

输出:

2^4 = 16 - mults: 3
2^5 = 32 - mults: 4