我想要计算在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;
}
发布于 2017-01-04 09:04:55
对于大型输入,您的程序将使用大量堆栈内存。
此外,f应该有相同的输入和输出类型(最初它有"unsigned long long“作为输入,int作为输出),否则结果将是错误的。
我建议您首先重写g而不使用递归,如果可行,请尝试研究如何使用尾递归来提高g的效率(当前变体可能不支持它)。
按照其他人的建议使用调试器也很好,特别是当它在调用“g”之前崩溃的时候。
最后,'num<0‘对于无符号的'num’没有意义。
https://stackoverflow.com/questions/41459744
复制