The link explains it fairly clearly. If F(n)
is the minimal number of steps to convert n
to 1
, then for any n > 1
we have the following recurrence relation:
F(n) = 1 + min(F(n-1), F(n/2), F(n/3)) // if n divisible by 2 and 3
F(n) = 1 + min(F(n-1), F(n/2)) // if n divisible by 2 and not 3
F(n) = 1 + min(F(n-1), F(n/3)) // if n divisible by 3 and not 2
F(n) = 1 + F(n-1) // all other cases
For your case, n=4
, we have to compute F(n-1)
and F(n/2)
to decide which one is minimum.
As for the second question, when n=10
we will evaluate first F(9)
. During this evaluation all values F(8), F(7), ... F(2)
are computed and memoized. Then, when we evaluate F(10/2) = F(5)
it will be simply a matter of looking up the value in the array of memoized values. This will save lots of computing.