Given two integers A and B, the task is to convert A to B with minimum number of following operations:
- Multiply A by any prime number.
- Divide A by one of its prime divisors.
Print the minimum number of operations required.
Input: A = 10, B = 15
Operation 1: 10 / 2 = 5
Operation 2: 5 * 3 = 15
Input: A = 9, B = 7
Naive Approach: If prime factorization of A = p1q1 * p2q2 * … * pnqn. If we multiply A by some prime then qi for that prime will increase by 1 and if we divide A by one of its prime factors then qi for that prime will decrease by 1. So for a prime p if it occurs qA times in prime factorization of A and qB times in prime factorization of B then we only need to find the sum of |qA – qB| for all the primes to get minimum number of operations.
Efficient Approach: Eliminate all the common factors of A and B by dividing both A and B by their GCD. If A and B have no common factors then we only need the sum of powers of their prime factors to convert A to B.
Below is the implementation of the above approach:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Minimum number operations required to convert n to m | Set-2
- Minimum number of operations to convert a given sequence into a Geometric Progression
- Convert a number m to n using minimum number of given operations
- Minimum splits required to convert a number into prime segments
- Minimum number of operations to convert array A to array B by adding an integer into a subarray
- Minimum operations required to convert X to Y by multiplying X with the given co-primes
- Number of steps to convert to prime factors
- Reduce N to 1 with minimum number of given operations
- Minimum number of operations required to reduce N to 1
- Form N by adding 1 or 2 in minimum number of operations X where X is divisible by M
- Minimum number of operations on an array to make all elements 0
- Find the minimum number to be added to N to make it a prime number
- Minimum number of operations on a binary string such that it gives 10^A as remainder when divided by 10^B
- Minimum number of operations required to make two strings equal
- Minimum number of increment/decrement operations such that array contains all elements from 1 to N
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.