Maximum prime moves to convert X to Y
Last Updated :
08 Mar, 2022
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.
Examples:
Input: X = 2, Y = 4
Output: 1
2 -> 4
Input: X = 5, Y = 6
Output: -1
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 repeatedly 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:
C++
#include <bits/stdc++.h>
using namespace std;
int maxOperations( int X, int Y)
{
if (X > Y)
return -1;
int diff = Y - X;
if (diff == 1)
return -1;
if (diff % 2 == 0)
return (diff / 2);
return (1 + ((diff - 3) / 2));
}
int main()
{
int X = 5, Y = 16;
cout << maxOperations(X, Y);
return 0;
}
|
Java
class GFG
{
static int maxOperations( int X, int Y)
{
if (X > Y)
return - 1 ;
int diff = Y - X;
if (diff == 1 )
return - 1 ;
if (diff % 2 == 0 )
return (diff / 2 );
return ( 1 + ((diff - 3 ) / 2 ));
}
public static void main(String []args)
{
int X = 5 , Y = 16 ;
System.out.println(maxOperations(X, Y));
}
}
|
Python3
def maxOperations(X, Y) :
if (X > Y) :
return - 1 ;
diff = Y - X;
if (diff = = 1 ) :
return - 1 ;
if (diff % 2 = = 0 ) :
return (diff / / 2 );
return ( 1 + ((diff - 3 ) / / 2 ));
if __name__ = = "__main__" :
X = 5 ; Y = 16 ;
print (maxOperations(X, Y));
|
C#
using System;
class GFG
{
static int maxOperations( int X, int Y)
{
if (X > Y)
return -1;
int diff = Y - X;
if (diff == 1)
return -1;
if (diff % 2 == 0)
return (diff / 2);
return (1 + ((diff - 3) / 2));
}
public static void Main(String []args)
{
int X = 5, Y = 16;
Console.WriteLine(maxOperations(X, Y));
}
}
|
Javascript
<script>
function maxOperations(X, Y)
{
if (X > Y)
return -1;
let diff = Y - X;
if (diff == 1)
return -1;
if (diff % 2 == 0)
return (diff / 2);
return (1 + ((diff - 3) / 2));
}
let X = 5, Y = 16;
document.write(maxOperations(X, Y));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...