我想计算在 Collatz 序列中有一个数字的递归调用的次数。但是对于这样一个更大的数字,例如 4565458458
#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int f(int value){
if(value==1) return 1;
else if(value%2 == 0) return value/2;
else return 3*value+1;
}
int g(int value){
if(value == 0) return 0;
if (f(value)==1) return 1;
return 1 + g(f(value));
}
int main(int argc, char *argv[]){
int nSteps=0;
istringstream iss(argv[1]);
int;
if(!(iss >> num).fail()){
if(num < 0) cout << "0" << endl;
else{
nSteps = g(num);
cout << "Result: " << nSteps << endl;
}
}
else{
cout << "Incorrect line paramaters: ./g n" << endl;
}
return 0;
}
最佳答案
您的程序将为大输入使用大量堆栈内存。
此外,f 应该具有相同的输入和输出类型(最初它的输入为“unsigned long long”,输出为 int),否则结果将是错误的。
我会建议您先不使用递归重写 g,如果可行,请尝试研究如何使 g 使用尾递归变得高效(当前变体可能不支持它)。
按照其他人的建议使用调试器也很好,尤其是在调用“g”之前崩溃的情况下。
最后,“num<0”对于无符号的“num”没有意义。
关于c++ - 递归时的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41459744/