Problem Statement:
On a positive integer, you can perform any one of the following 3 steps.
Subtract 1 from it. ( n = n - 1 )
If its divisible by 2, divide by 2. ( if n % 2 == 0 , then n = n / 2 )
If its divisible by 3, divide by 3. ( if n % 3 == 0 , then n = n / 3 )
Given a positive integer n and you task is find the minimum number of steps that takes n to one .
My Recursive Solution (in C++) compares all the 3 cases when N is divisible by 3, while the general solution compares only 2, but still gives the correct solution.
int min_steps(int N){
if(N==1) return 0;
else{
if(N%3==0){
if(N%2==0)
return (1+min(min_steps(N/3),min_steps(N/2),min_steps(N-1)));
else
return(1+min(min_steps(N/3),min_steps(N-1)));
}
else if(N%2==0){
return(1+min(min_steps(N/2),min_steps(N-1)));
}
else
return(1+min_steps(N-1));
}
}
But the general solution is,
int min_steps(int N){
if(N==1) return 0;
else{
if(N%3==0){
return(1+min(min_steps(N/3),min_steps(N-1)));
}
else if(N%2==0){
return(1+min(min_steps(N/2),min_steps(N-1)));
}
else
return(1+min_steps(N-1));
}
}
My question is, how come we don't compare all the 3 cases but still derive at the correct solution. I cannot follow the general solution's algorithm. Any help for letting me understand would be appreciated hugely.