Minimum cost to reduce the integer N to 1 as per given conditions | Function to find the minimum cost to reduce the integer N to 1 by the given operations ; Check if x is 1 ; Print the answer ; Prestore the answer ; Iterate till n exists ; Divide N by x ; Reduce n by x ; Add the cost ; Update the answer ; Return the answer ; Initialize the variables ; Function call
function min_cost ( n , x , p , q ) { if ( x == 1 ) { document . write ( ( n - 1 ) * p + " " ) ; return 0 ; } let ans = ( n - 1 ) * p ; let pre = 0 ; while ( n > 1 ) { let tmp = Math . floor ( n / x ) ; if ( tmp < 0 ) break ; pre += ( n - tmp * x ) * p ; n = Math . floor ( n / x ) pre += q ; ans = Math . min ( ans , pre + ( n - 1 ) * p ) ; } return ans ; } let n = 5 , x = 2 , p = 2 , q = 3 ; document . write ( min_cost ( n , x , p , q ) ) ;