Minimum cost to convert M to N by repeated addition of its even divisors | C ++ program for the above approach ; Function to find the value of minimum steps to convert m to n ; Base Case ; If n exceeds m ; Iterate through all possible even divisors of m ; If m is divisible by i , then find the minimum cost ; Add the cost to convert m to m + i and recursively call next state ; Return min_cost ; Driver code ; Function call ; If conversion is not possible ; Print the cost
#include <iostream> NEW_LINE using namespace std ; int inf = 1000000008 ; int minSteps ( int m , int n ) { if ( n == m ) return 0 ; if ( m > n ) return inf ; int min_cost = inf ; for ( int i = 2 ; i < m ; i += 2 ) { if ( m % i == 0 ) { min_cost = min ( min_cost , m / i + minSteps ( m + i , n ) ) ; } } return min_cost ; } int main ( ) { int M = 6 ; int N = 24 ; int minimum_cost = minSteps ( M , N ) ; if ( minimum_cost == inf ) minimum_cost = -1 ; cout << minimum_cost ; return 0 ; }