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
var primes = Array ( 1000006 ) . fill ( 0 ) ; function gcd ( a , b ) { if ( b == 0 ) return a ; else return gcd ( b , a % b ) ; } function preprocess ( ) { for ( i = 1 ; i <= 1000000 ; i ++ ) primes [ i ] = i ; for ( i = 2 ; i * i <= 1000000 ; i ++ ) { if ( primes [ i ] == i ) { for ( j = 2 * i ; j <= 1000000 ; j += i ) { if ( primes [ j ] == j ) primes [ j ] = i ; } } } } function Steps ( x , m ) { var steps = 0 ; var flag = false ; while ( x > 1 ) { if ( primes [ x ] > m ) { flag = true ; break ; } x /= primes [ x ] ; steps ++ ; } if ( flag ) return - 1 ; return steps ; } function minimumSteps ( x , y , m ) { preprocess ( ) ; var g = gcd ( x , y ) ; x = x / g ; y = y / g ; var x_steps = Steps ( x , m ) ; var y_steps = Steps ( y , m ) ; if ( x_steps == - 1 y_steps == - 1 ) return - 1 ; return x_steps + y_steps ; } var X = 160 ; var Y = 180 ; var M = 10 ; document . write ( minimumSteps ( X , Y , M ) ) ;