Minimum number of operations to convert a given sequence into a Geometric Progression | Set 2 | Function to find minimum cost ; Sort the array ; Maximum possible common ratios ; Iterate over all possible common ratios ; Calculate operations required for the current common ratio ; Calculate minimum cost ; Given N ; Given arr [ ] ; Function Calling
function minCost ( arr , n ) { if ( n == 1 ) { document . write ( 0 ) ; return ; } arr . sort ( ( a , b ) => a - b ) ; var raised = 1 / ( n - 1 ) ; var temp = Math . pow ( arr [ n - 1 ] , raised ) ; var r = Math . round ( temp ) + 1 ; var i , j , min_cost = 1000000000 ; var common_ratio = 1 ; for ( j = 1 ; j <= r ; j ++ ) { var curr_cost = 0 , prod = 1 ; for ( i = 0 ; i < n ; i ++ ) { curr_cost += Math . abs ( arr [ i ] - prod ) ; prod *= j ; if ( curr_cost >= min_cost ) break ; } if ( i == n ) { min_cost = Math . min ( min_cost , curr_cost ) ; common_ratio = j ; } } document . write ( min_cost + ' ' ) ; document . write ( common_ratio + ' ' ) ; } var N = 6 ; var arr = [ 1 , 11 , 4 , 27 , 15 , 33 ] ; minCost ( arr , N ) ;