我在弄清楚如何以power2的计数器等于power1的方式增加计数(代码中的mult)时遇到了一些麻烦。我的程序以不同的方式比较了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
最佳答案
您需要在调用之间重置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;
}
关于c++ - 如何计算递归调用的次数? (计算x ^ n的乘法数),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49020508/