Minimum repeated addition of even divisors of N required to convert N to M | INF is the maximum value which indicates Impossible state ; Stores the dp states ; Recursive Function that considers all possible even divisors of cur ; Indicates impossible state ; Check dp [ cur ] is already calculated or not ; Initially it is set to INF that meanswe cur can 't be transform to M ; Loop to find even divisors of cur ; if i is divisor of cur ; if i is even ; Find recursively for cur + i ; Check another divisor ; Find recursively for cur + ( cur / i ) ; Finally store the current state result and return the answer ; Function that counts the minimum operation to reduce N to M ; Initialise dp state ; Function Call ; Driver code ; Given N and M ; Function Call ; INF indicates impossible state
INF = 10000007 ; NEW_LINE max_size = 100007 ; NEW_LINE dp = [ 0 for i in range ( max_size ) ] ; NEW_LINE def min_op ( cur , M ) : NEW_LINE INDENT if ( cur > M ) : NEW_LINE INDENT return INF ; NEW_LINE DEDENT if ( cur == M ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( dp [ cur ] != - 1 ) : NEW_LINE INDENT return dp [ cur ] ; NEW_LINE DEDENT op = INF ; NEW_LINE i = 2 NEW_LINE while ( i * i <= cur ) : NEW_LINE INDENT if ( cur % i == 0 ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT op = min ( op , 1 + min_op ( cur + i , M ) ) ; NEW_LINE DEDENT if ( ( cur // i ) != i and ( cur // i ) % 2 == 0 ) : NEW_LINE INDENT op = min ( op , 1 + min_op ( cur + ( cur // i ) , M ) ) NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT dp [ cur ] = op ; NEW_LINE return op NEW_LINE DEDENT def min_operations ( N , M ) : NEW_LINE INDENT for i in range ( N , M + 1 ) : NEW_LINE INDENT dp [ i ] = - 1 ; NEW_LINE DEDENT return min_op ( N , M ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 6 NEW_LINE M = 24 NEW_LINE op = min_operations ( N , M ) ; NEW_LINE if ( op >= INF ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( op ) NEW_LINE DEDENT DEDENT