Minimum multiplications with { 2 , 3 , 7 } to make two numbers equal | Function to find powers of 2 , 3 and 7 in x ; To keep count of each divisor ; To store the result ; Count powers of 2 in x ; Count powers of 3 in x ; Count powers of 7 in x ; Remaining number which is not divisible by 2 , 3 or 7 ; Function to return the minimum number of given operations required to make a and b equal ; a = x * 2 ^ a1 * 3 ^ a2 * 7 ^ a3 va [ 0 ] = a1 va [ 1 ] = a2 va [ 2 ] = a3 va [ 3 ] = x ; Similarly for b ; If a and b cannot be made equal with the given operation . Note that va [ 3 ] and vb [ 3 ] contain remaining numbers after repeated divisions with 2 , 3 and 7. If remaining numbers are not same then we cannot make them equal . ; Minimum number of operations required ; Driver code
function Divisors ( x ) { var c = 0 ; var v = [ ] ; while ( x % 2 == 0 ) { c ++ ; x /= 2 ; } v . push ( c ) ; c = 0 ; while ( x % 3 == 0 ) { c ++ ; x /= 3 ; } v . push ( c ) ; c = 0 ; while ( x % 7 == 0 ) { c ++ ; x /= 7 ; } v . push ( c ) ; v . push ( x ) ; return v ; } function MinOperations ( a , b ) { var va = Divisors ( a ) ; var vb = Divisors ( b ) ; if ( va [ 3 ] != vb [ 3 ] ) { return - 1 ; } var minOperations = Math . abs ( va [ 0 ] - vb [ 0 ] ) + Math . abs ( va [ 1 ] - vb [ 1 ] ) + Math . abs ( va [ 2 ] - vb [ 2 ] ) ; return minOperations ; } var a = 14 , b = 28 ; document . write ( MinOperations ( a , b ) ) ;