C ++ segmentation error in recursive function

Why am I getting a segmentation error in my recursive function. This happens every time I call it when the value is greater than 4 as a parameter

#include <iostream>
#include <limits>

using namespace std;    

int printSeries(int n){
    if(n==1){       
        return 1;
    }
    else if( n==2){     
        return 2;
    }
    else if( n==3){
        return 3;
    }
    else if( n==4){
        return printSeries(1) + printSeries(2) + printSeries(3);
    }
    else{       
        return printSeries(n-3) + printSeries((n-2) + printSeries(n-1));
    }
}


int main(){

        //double infinity = numeric_limits<double>::max();

        for(int i=1; i<=10; i++){
            cout << printSeries(i) << endl;
        }

    return 0;

}

This works fine, but I'm not sure if it will return the correct result:

return printSeries(n-3) + printSeries(n-2) + printSeries(n-1);
+3
source share
2 answers
return printSeries(n-3) + printSeries( (n-2) + printSeries(n-1) );
//                                     ^^^^^^^^^^^^^^^^^^^^^^^^

Incorrect nesting of brackets causes infinite recursion, which leads to stack overflow (segfault).

Consider when n = 4,

f(4) = 1 + f(2 + f(3))
     = 1 + f(2 + 3)
     = 1 + f(5)
     = 1 + [ f(2) + f(3 + f(4)) ]
     = ...
+18
source

The parenthesis problem mentioned above is a source of infinite recursion. But there is another problem with the code, even if you copy the parentheses for case 5 as case 4:

printSeries (4) printSeries 3 .
printSeries (5) printSeries 6 .
printSeries (6) printSeries 12 .
printSeries (10) printSeries 156 .
printSeries (20) printSeries 69747 .
printSeries (50) printSeries 6 .

, , . , ?

+4

Source: https://habr.com/ru/post/1743393/


All Articles