Given two integers X and Y, the task is to convert X to Y using the following operations:
- Add any prime number to X.
- Subtract any prime number from Y.
Print the maximum number of such operations required or -1 if it is not possible to convert X to Y.
Input: X = 2, Y = 4
2 -> 4
Input: X = 5, Y = 6
It is impossible to convert 5 to 6
with the given operations.
Approach: As the task is to maximize the operations, so the minimum possible value must be added to X in every operation. Since the value has to be prime, so the minimum two primes i.e. 2 and 3 can be used as they both are prime and can cover both even and odd parity. Now, there are three cases:
- If X > Y then the answer will be -1 as X cannot be made equal to Y with the given operation.
- If X = Y then the answer will be 0.
- If X < Y then calculate P = Y – X and,
- If P = 1 then the answer will be -1 as 1 is not prime and it cannot be added or subtracted.
- If P is even then 2 can be repetedly added to X and the answer will be P / 2
- If P is even then add 3 to X and then 2 can again be repeatedly added to the new X to make it equal to Y, the result in this case will be 1 + ((P – 3) / 2).
Below is the implementation of the above approach:
Time Complexity: O(1)
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
- Number of steps to convert to prime factors
- Minimum prime number operations to convert A to B
- Minimum splits required to convert a number into prime segments
- Sum of all the prime numbers with the maximum position of set bit ≤ D
- Maximum number of unique prime factors
- Maximum no. of contiguous Prime Numbers in an array
- Find prime number K in an array such that (A[i] % K) is maximum
- Find sum of a number and its maximum prime factor
- Minimum and Maximum prime numbers in an array
- Queries for maximum difference between prime numbers in given ranges
- Find the row whose product has maximum count of prime factors
- Sum of Maximum and Minimum prime factor of every number in the Array
- Minimum and Maximum Prime Numbers of a Singly Linked List
- Number which has the maximum number of distinct prime factors in the range M to N
- Maximum possible prime divisors that can exist in numbers having exactly N divisors
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.