Minimize steps required to make two values equal by repeated division by any of their prime factor which is less than M | Stores the prime factor of numbers ; Function to find GCD of a and b ; Base Case ; Otherwise , calculate GCD ; Function to precompute the prime numbers till 1000000 ; Initialize all the positions with their respective values ; Iterate over the range [ 2 , sqrt ( 10 ^ 6 ) ] ; If i is prime number ; Mark it as the factor ; Utility function to count the number of steps to make X and Y equal ; Initialise steps ; Iterate x is at most 1 ; Divide with the smallest prime factor ; If X and Y can 't be  made equal ; Return steps ; Function to find the minimum number of steps required to make X and Y equal ; Generate all the prime factors ; Calculate GCD of x and y ; Divide the numbers by their gcd ; If not possible , then return - 1 ; Return the resultant number of steps ; Driver Code
primes = [ 0 ] * ( 1000006 ) NEW_LINE def gcd ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT else : NEW_LINE INDENT return gcd ( b , a % b ) NEW_LINE DEDENT DEDENT def preprocess ( ) : NEW_LINE INDENT for i in range ( 1 , 1000001 ) : NEW_LINE INDENT primes [ i ] = i NEW_LINE DEDENT i = 2 NEW_LINE while ( i * i <= 1000000 ) : NEW_LINE INDENT if ( primes [ i ] == i ) : NEW_LINE INDENT for j in range ( 2 * i , 1000001 , i ) : NEW_LINE INDENT if ( primes [ j ] == j ) : NEW_LINE INDENT primes [ j ] = i NEW_LINE DEDENT DEDENT DEDENT i += 1 NEW_LINE DEDENT DEDENT def Steps ( x , m ) : NEW_LINE INDENT steps = 0 NEW_LINE flag = False NEW_LINE while ( x > 1 ) : NEW_LINE INDENT if ( primes [ x ] > m ) : NEW_LINE INDENT flag = True NEW_LINE break NEW_LINE DEDENT x //= primes [ x ] NEW_LINE steps += 1 NEW_LINE DEDENT if ( flag != 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return steps NEW_LINE DEDENT def minimumSteps ( x , y , m ) : NEW_LINE INDENT preprocess ( ) NEW_LINE g = gcd ( x , y ) NEW_LINE x = x // g NEW_LINE y = y // g NEW_LINE x_steps = Steps ( x , m ) NEW_LINE y_steps = Steps ( y , m ) NEW_LINE if ( x_steps == - 1 or y_steps == - 1 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return x_steps + y_steps NEW_LINE DEDENT X = 160 NEW_LINE Y = 180 NEW_LINE M = 10 NEW_LINE print ( minimumSteps ( X , Y , M ) ) NEW_LINE