【发布时间】:2017-01-04 08:56:31
【问题描述】:
我想计算在 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;
}
【问题讨论】:
-
欢迎来到 Stack Overflow!听起来您可能需要学习如何使用debugger 来单步执行您的代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。进一步阅读:How to debug small programs.
-
如果你递归足够多,你很可能会发生堆栈溢出
-
程序不正确,无法编译,因为下面的错误
:24:17: error: ‘num’ was not declared in this scope。 -
@Nemanja Trifunovic - num-declaration 被不正确的编辑删除。
标签: c++ recursion segmentation-fault collatz