Minimum cost to convert M to N by repeated addition of its even divisors | Javascript program to implement 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
let inf = 1000000008 ; function minSteps ( m , n ) { if ( n == m ) return 0 ; if ( m > n ) return inf ; let min_cost = inf ; for ( let i = 2 ; i < m ; i += 2 ) { if ( m % i == 0 ) { min_cost = Math . min ( min_cost , m / i + minSteps ( m + i , n ) ) ; } } return min_cost ; } let M = 6 ; let N = 24 ; let minimum_cost = minSteps ( M , N ) ; minimum_cost = minimum_cost == inf ? - 1 : minimum_cost ; document . write ( minimum_cost ) ;