c++ - 递归时的段错误

标签 c++ recursion segmentation-fault collatz

我想计算在 Collat​​z 序列中有一个数字的递归调用的次数。但是对于这样一个更大的数字,例如 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/

相关文章:

c - 使用 strcat() 的段错误

c++ - "template <class T, class C>"和 "template <class T> template <class C>"有什么区别

recursion - F# 递归与迭代速度/开销

c - 二叉树实现中的段错误

linux - 递归应用fold命令linux修改目录中的所有文件

c# - 将递归方法转换为非递归 C#

c - 尝试复制数组 C 时出现段错误(核心已转储)

c++ - 使用运算符重载的多项式运算

C++,find_if 不工作

c++ - cpp 文件中是否需要 __declspec(dllexport)