Minimize operations required to obtain N | Function to find the minimum number of operations ; Storing the minimum operations to obtain all numbers up to N ; Initilal state ; Iterate for the remaining numbers ; If the number can be obtained by multiplication by 2 ; If the number can be obtained by multiplication by 3 ; Obtaining the number by adding 1 ; Return the minm operations to obtain n ; Driver code
function minOperations ( n ) { let dp = new Array ( n + 1 ) ; dp [ 1 ] = 0 ; for ( let i = 2 ; i <= n ; i ++ ) { dp [ i ] = Number . MAX_VALUE ; if ( i % 2 == 0 ) { let x = dp [ parseInt ( i / 2 , 10 ) ] ; if ( x + 1 < dp [ i ] ) { dp [ i ] = x + 1 ; } } if ( i % 3 == 0 ) { let x = dp [ parseInt ( i / 3 , 10 ) ] ; if ( x + 1 < dp [ i ] ) { dp [ i ] = x + 1 ; } } let x = dp [ i - 1 ] ; if ( x + 1 < dp [ i ] ) { dp [ i ] = x + 1 ; } } return dp [ n ] ; } let n = 15 ; document . write ( minOperations ( n ) ) ;