我有这个递归函数,它在其素因子中分解一个数字,并显示结果标准输出例如
descompon(2, 10);
输出
2 = 2
3 = 3
4 = 2^2
5 = 5
6 = 2 * 3
7 = 7
8 = 2^3
9 = 3^2
10 = 2 * 5
代码
#include <iostream>
#include <sstream>
int comprobar_primo( int* num, int e )
{
if (*num%e == 0)
{
*num /= e;
return 1 + comprobar_primo(num, e);
}
return 0;
}
std::string factor_primo(int a, int b, std::stringstream& fact)
{
unsigned exp = comprobar_primo(&a, b);
if (exp >= 1)
{
fact << b;
if (exp > 1) fact << '^' << exp;
if (a != 1) fact << " * ";
}
if (a > 1) factor_primo(a, b + 1, fact);
return fact.str();
}
void descompon(int a, int b, int ver)
{
std::stringstream fact;
//std::string result = factor_primo(a, 2, fact);
if(ver)
std::cout << a << " = " << factor_primo(a, 2, fact) << std::endl;
if(a < b)
descompon( a + 1, b, ver);
}
int main(void)
{
descompon(2, 10000, 1);
return 0;
}
问题是当达到5922时程序仍然冻结,显示:
Process returned -1073741819 <0xC0000005>
为什么会发生这种情况以及如何避免?
答案 0 :(得分:0)
factor_primo
和descompon
函数都可能导致堆栈溢出。最好将它们转换为迭代版本。修改后的代码如下:
// no need to pass b as argument since we start from b=2 and increment b by 1
std::string factor_primo(int a, std::stringstream& fact)
{
for(int b=2; a>1; b++)
{
if(a%b==0)
{
unsigned exp=comprobar_primo(&a, b);
if(exp >= 1)
{
fact << b;
if(exp > 1) fact << '^' << exp;
if(a != 1) fact << " * ";
}
}
}
return fact.str();
}
void descompon(int a, int b, int ver)
{
if(ver)
{
for(int i=a; i<=b; i++) {
std::stringstream fact;
std::cout << i << " = " << factor_primo(i, fact) << std::endl;
}
}
}
int main(void)
{
descompon(2, 10000, 1);
getchar();
return 0;
}