Make two numbers equal by mutiplying with their prime factors minimum number of times
Given two numbers X and Y, the task is to make both of them equal by repeatedly multiplying with their prime factors minimum number of times.
Input: X = 36, Y = 48
Operation 1: Choose 2(prime factor of X) and multiply with X. Now, X = 72, Y = 48.
Operation 2: Choose 2(prime factor of X) and multiply with X, Now, X = 144, Y = 48
Operation 3: Choose 3(prime factor of Y) and multiply with X. Now, X = 144, Y = 144
Input: X = 10, Y = 14
Approach: The idea is that X and Y can be made equal only if every prime factor of X is present in Y and every prime factor of Y is present in X. To count the minimum operations required to make them equal, follow the following steps:
- Calculate the gcd of X and Y, say GCD and find newX = X / GCD and newY = Y / GCD to remove the common prime factors.
- Find the prime factors with their frequencies of both newX and newY.
- Check every prime factor of newX is present in Y(will divide Y) and every prime factor of newY is present in X(will divide X). If not, then return -1.
- Initialize a variable, say ans =0, to store the number of operations required.
- Add all the frequencies of primes of newX and newY to the ans.
- Return the ans.
Below is the implementation of the above approach:
Time Complexity: O(sqrt(max(X, Y)))
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.