Minimum repeated addition of even divisors of N required to convert N to M | INF is the maximum value which indicates Impossible state ; Recursive Function that considers all possible even divisors of cur ; Indicates impossible state ; Return 0 if cur == M ; Initially it is set to INF that means we can 't transform cur to M ; Loop to find even divisors of cur ; if i is divisor of cur ; if i is even ; Finding divisors recursively for cur + i ; Check another divisor ; Find recursively for cur + ( cur / i ) ; Return the answer ; Function that finds the minimum operation to reduce N to M ; INF indicates impossible state ; Given N and M ; Function Call
let INF = 1e7 ; function min_op ( cur , M ) { if ( cur > M ) return INF ; if ( cur == M ) return 0 ; let op = INF ; for ( let i = 2 ; i * i <= cur ; i ++ ) { if ( cur % i == 0 ) { if ( i % 2 == 0 ) { op = Math . min ( op , 1 + min_op ( cur + i , M ) ) ; } if ( ( cur / i ) != i && ( cur / i ) % 2 == 0 ) { op = Math . min ( op , 1 + min_op ( cur + ( cur / i ) , M ) ) ; } } } return op ; } function min_operations ( N , M ) { let op = min_op ( N , M ) ; if ( op >= INF ) document . write ( " " ) ; else document . write ( op + " " ) ; } let N = 6 , M = 24 ; min_operations ( N , M ) ;