Minimum cost to reduce A and B to 0 using square root or divide by 2 | Function to return the minimum cost of converting A and B to 0 ; If both A and B doesn 't change in  this recusrive call, then return INT_MAX  to save the code from going into  infinite loop ; Base Case ; If the answer of this recursive call is already memoised ; If A is reduced to A / 2 ; If B is reduced to B / 2 ; If both A and B is reduced to sqrt ( A * B ) ; Return the minimum of the value given by the above three subproblems , also memoize the value while returning ; Driver Code
function getMinOperations ( A , B , prevA , prevB , dp ) { if ( A == prevA && B == prevB ) { return Number . MAX_SAFE_INTEGER ; } if ( A == 0 && B == 0 ) { return 0 ; } if ( dp [ A ] [ B ] != - 1 ) { return dp [ A ] [ B ] ; } let ans1 = getMinOperations ( Math . floor ( A / 2 ) , B , A , B , dp ) ; if ( ans1 != Number . MAX_SAFE_INTEGER ) { ans1 += 1 ; } let ans2 = getMinOperations ( A , Math . floor ( B / 2 ) , A , B , dp ) ; if ( ans2 != Number . MAX_SAFE_INTEGER ) { ans2 += 1 ; } let ans3 = getMinOperations ( Math . floor ( Math . sqrt ( A * B ) ) , Math . floor ( Math . sqrt ( A * B ) ) , A , B , dp ) ; if ( ans3 != Number . MAX_SAFE_INTEGER ) { ans3 += 2 ; } return ( dp [ A ] [ B ] = Math . min ( ans1 , Math . min ( ans2 , ans3 ) ) ) ; } let A = 53 , B = 16 ; let mx = Math . max ( A , B ) ; let dp = new Array ( mx + 1 ) . fill ( 0 ) . map ( ( ) => new Array ( mx + 1 ) . fill ( - 1 ) ) ; document . write ( getMinOperations ( A , B , - 1 , - 1 , dp ) ) ;