3. Min Steps to 1 #

Created Monday 09 March 2020

Given a positive integer n, find the minimum number of steps s, that takes n to 1. You can perform any one of the following 3 steps.

1.) Subtract 1 from it. (n= n - ­1) , 2.) If its divisible by 2, divide by 2.( if n%2==0, then n= n/2 ) , 3.) If its divisible by 3, divide by 3. (if n%3 == 0, then n = n / 3 ).

WAP to do this. note: The idea that 3 divides in the most basic parts, then divide by 2 then -1. This is **wrong, **as seen from a simple case of 10. This is because we do not know the factors of the numbers.


Soln: We follow the three steps to get to DP.

  1. Bruteforce
    1. If n is 1 return 0, no steps required.
    2. Init n1 = n, n2 = n, n3 = n. This is the maximum value n1, n2 and n3 can have. So that there’s no need for INT_MAX and minimum function can be handled easily.
    3. If n%2==0, n1 = f(n/2) + 1; // counting this step
    4. 2 and n3If n%3==0, n2 = f(n/3) +1; // counting this step
    5. n3 = f(n-1) + 1;
    6. return minimum(n1, n2, n3);
  2. Memoization - top down approach
  1. DP bottom up solution

Proof: