Minimum cost to reduce the integer N to 1 as per given conditions | Java program for the above approach ; 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
import java . util . * ; class GFG { static int min_cost ( int n , int x , int p , int q ) { if ( x == 1 ) { System . out . println ( ( n - 1 ) * p ) ; return 0 ; } int ans = ( n - 1 ) * p ; int pre = 0 ; while ( n > 1 ) { int tmp = n / x ; if ( tmp < 0 ) break ; pre += ( n - tmp * x ) * p ; n /= x ; pre += q ; ans = Math . min ( ans , pre + ( n - 1 ) * p ) ; } return ans ; } public static void main ( String [ ] args ) { int n = 5 , x = 2 , p = 2 , q = 3 ; System . out . println ( min_cost ( n , x , p , q ) ) ; } }