Solution: Primitive Calculator

Solve the Primitive Calculator Problem.

We'll cover the following

Solution

Let calculator(n)calculator(n) be the minimum number of operations needed to get nn from 11. Since the last operation in an optimum sequence of operations is “+1+1,” “×2×2,” or “×3×3,” we get the following recurrence relation, for n1n ≥ 1:

calculator(n)=1+min{calculator(n1)calculator(n/2)amp;if   n  is divisible by  2,calculator(n/3)amp;if   n  is divisible by  3.calculator(n) = 1 + min \begin{cases} calculator(n-1) \\ calculator(n/2) & \text{if }~~ n~~ \text{is divisible by}~~ 2, \\ calculator(n/3) & \text{if }~~ n~~ \text{is divisible by}~~ 3. \end{cases}

This recurrence relation, together with the base case calculator(1)=1calculator(1) = 1, can be mechanically converted into a recursive and then an iterative algorithm.


 Calculator(n)Calculator(n):
 table[1..n][+,...,+]table[1..n] ← [+∞, . . . , +∞]
 table[1]0table[1] ← 0
 for kk from 22 to nn:
table[k]=1+table[k1]table[k] = 1 + table[k − 1]
 if nn is divisible by 22:
  table[k]=min(table[k],1+table[k/2])table[k]=min(table[k],1+table[k/2])
 if nn is divisible by 33:
  table[k]=min(table[k],1+table[k/3])table[k]=min(table[k],1+table[k/3])
 return table[n]table[n]


Recall, however, that besides the optimum value, we are asked to output an optimum sequence of operations. To do this, notice that we can find the last operation as follows:

  • it is “+1+1,” if calculator(n)=1+calculator(n1)calculator(n)=1+calculator(n−1);
  • it is “×2×2,” if nn is divisible by 22 and calculator(n)=1+calculator(n/2)calculator(n) = 1 + calculator(n/ 2);
  • it is “×3×3,” if nn is divisible by 33 and calculator(n)=1+calculator(n/3)calculator(n) = 1 + calculator(n/ 3).

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.