Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How I fix my code that gives segmentation fault?

My code gives Segmentation fault when i run it.I do not understand its reason.Why?

input 4 6

int solve(int s, int f){
    if(s==f){
            return 0;
    }
    if(s>f){
            return s-f;
    }
    if(s>=0){
    return min(solve(s-1,f)+1,solve(s*2,f)+1);
    }
    else{
    return 0;
    }
}
int main(){
    int n,m;
    cin>>n>>m;
    cout<<solve(n,m)<<'\n';
    return 0;
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have infinite recursion. For your example input 4 6, you call:

// from main: 
solve(4, 6)
// inside that call we have
min(solve(3, 6)+1, solve(8, 6)+1);
//  ^ from this one
min(solve(2, 6)+1, solve(6, 6)+1);
//  ^ from this one
min(solve(1, 6)+1, solve(4, 6)+1);
//                 ^ back to beginning

I don’t know what this program is supposed to do, but you need to rethink your algorithm.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading