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 ; Driver Code ; Initialize the variables ; Function call
def min_cost ( n , x , p , q ) : NEW_LINE INDENT if ( x == 1 ) : NEW_LINE INDENT print ( ( n - 1 ) * p ) NEW_LINE return 0 NEW_LINE DEDENT ans = ( n - 1 ) * p NEW_LINE pre = 0 NEW_LINE while ( n > 1 ) : NEW_LINE INDENT tmp = n // x NEW_LINE if ( tmp < 0 ) : NEW_LINE break NEW_LINE pre += ( n - tmp * x ) * p NEW_LINE n //= x NEW_LINE pre += q NEW_LINE ans = min ( ans , pre + ( n - 1 ) * p ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 ; x = 2 ; NEW_LINE p = 2 ; q = 3 ; NEW_LINE print ( min_cost ( n , x , p , q ) ) NEW_LINE DEDENT