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;
}
>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.