Minimum cost to reach a point N from 0 with two different operations allowed | Function to return minimum cost to reach destination ; Initialize cost to 0 ; going backwards until we reach initial position ; if 2 * X jump is better than X + 1 ; if X + 1 jump is better ; return cost ; Driver Code
function minCost ( N , P , Q ) { var cost = 0 ; while ( N > 0 ) { if ( N & 1 ) { cost += P ; N -- ; } else { var temp = parseInt ( N / 2 ) ; if ( temp * P > Q ) cost += Q ; else cost += P * temp ; N = parseInt ( N / 2 ) ; } } return cost ; } var N = 9 , P = 5 , Q = 1 ; document . write ( minCost ( N , P , Q ) ) ;