|
| 1 | +#include<iostream> |
| 2 | +#include<climits> |
| 3 | +using namespace std; |
| 4 | +int Minsteps_3(int n){ |
| 5 | + int *ans=new int[n+1]; |
| 6 | + ans[0]=0; |
| 7 | + ans[1]=0; |
| 8 | + for(int i=2;i<=n;i++){ |
| 9 | + int a=INT_MAX,b=INT_MAX,c=INT_MAX; |
| 10 | + a=ans[i-1]+1; |
| 11 | + if(i%2==0){ |
| 12 | + b=ans[i/2]+1; |
| 13 | + } |
| 14 | + if(i%3==0){ |
| 15 | + c=ans[i/3]+1; |
| 16 | + } |
| 17 | + ans[i]=min(a,min(b,c)); |
| 18 | + } |
| 19 | + return ans[n]; |
| 20 | +} |
| 21 | +int Minsteps_helper(int n,int *ans){ |
| 22 | + if(n<=1){ |
| 23 | + return 0; |
| 24 | + } |
| 25 | + if(ans[n]!=-1){ |
| 26 | + return ans[n]; |
| 27 | + } |
| 28 | + int x=Minsteps_helper(n-1,ans); |
| 29 | + int y=INT_MAX,z=INT_MAX; |
| 30 | + if(n%2==0){ |
| 31 | + y=Minsteps_helper(n/2,ans); |
| 32 | + } |
| 33 | + if(n%3==0){ |
| 34 | + z=Minsteps_helper(n/3,ans); |
| 35 | + } |
| 36 | + int output=min(x,min(y,z))+1; |
| 37 | + ans[n]=output; |
| 38 | + return ans[n]; |
| 39 | +} |
| 40 | +int Minsteps_2(int n){ |
| 41 | + int *ans=new int[n+1]; |
| 42 | + for(int i=0;i<=n;i++){ |
| 43 | + ans[i]=-1; |
| 44 | + } |
| 45 | + return Minsteps_helper(n,ans); |
| 46 | +} |
| 47 | +int Minsteps(int n){ |
| 48 | + if(n<=1){ |
| 49 | + return 0; |
| 50 | + } |
| 51 | + int x=Minsteps(n-1); |
| 52 | + int y=INT_MAX,z=INT_MAX; |
| 53 | + if(n%2==0){ |
| 54 | + y=Minsteps(n/2); |
| 55 | + } |
| 56 | + if(n%3==0){ |
| 57 | + z=Minsteps(n/3); |
| 58 | + } |
| 59 | + return min(x,min(y,z))+1; |
| 60 | +} |
| 61 | +int main(){ |
| 62 | + int n; |
| 63 | + cout<<"Enter the Number: "<<endl; |
| 64 | + cin>>n; |
| 65 | + cout<<Minsteps_3(n)<<endl; |
| 66 | + return 0; |
| 67 | +} |
0 commit comments