I need to write a function (in C++) the gets two integer numbers (>0) (n1,n2).
I can do only two things:
- add 1 to n1.
- multiply n1 by 2.
The function returns the number of steps of the shortest way from n1 to n2.
Can you give me ideas how to do it?
Thank you!
P.S.
If it’s impossible the function returns -1.
here What I tried:
if (n1<n2)
{
n1++;
if ((n1)*2<=n2)
return 2+f(n1*2,n2);
else
return 1+f(n1,n2);
}
I suppose it is best to turn the problem around: Go from n2 to n1 with these two tings:
This way you are able to find the biggest steps when you first try to divide the number by 2 and if that is not possible subtract by 1 (after which dividing works). COntinue doing this until your reach n1 (or a lower value, after which you only can use the ‘decrease step’ and thus basically know the required amount of steps already)
I suppose you can implement this algorithm by yourself…