给定两个整数X和Y ,任务是使用以下操作将X转换为Y :
- 将任何质数添加到X 。
- 从Y 中减去任何素数。
如果无法将X转换为Y ,则打印所需的此类操作的最大数量或-1 。
例子:
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.
方法:由于任务是最大化操作,所以必须在每次操作中将最小可能值添加到X。由于该值必须是质数,因此可以使用最小的两个质数,即2和3,因为它们都是质数并且可以涵盖偶数和奇数奇偶校验。现在分三种情况:
- 如果X > Y则答案将为-1,因为使用给定的操作无法使X等于Y。
- 如果X = Y那么答案将是0 。
- 如果X < Y则计算P = Y – X并且,
- 如果P = 1,那么答案将是-1,因为1不是素数,不能加减。
- 如果P是偶数,那么2可以重复添加到 X 中,答案将是P / 2
- 如果P是偶数,则将3添加到X然后可以再次将2重复添加到新的X以使其等于Y ,在这种情况下,结果将是1 + ((P – 3) / 2) 。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the maximum operations
// required to convert X to Y
int maxOperations(int X, int Y)
{
// X cannot be converted to Y
if (X > Y)
return -1;
int diff = Y - X;
// If the difference is 1
if (diff == 1)
return -1;
// If the difference is even
if (diff % 2 == 0)
return (diff / 2);
// Add 3 to X and the new
// difference will be even
return (1 + ((diff - 3) / 2));
}
// Driver code
int main()
{
int X = 5, Y = 16;
cout << maxOperations(X, Y);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function to return the maximum operations
// required to convert X to Y
static int maxOperations(int X, int Y)
{
// X cannot be converted to Y
if (X > Y)
return -1;
int diff = Y - X;
// If the difference is 1
if (diff == 1)
return -1;
// If the difference is even
if (diff % 2 == 0)
return (diff / 2);
// Add 3 to X and the new
// difference will be even
return (1 + ((diff - 3) / 2));
}
// Driver code
public static void main(String []args)
{
int X = 5, Y = 16;
System.out.println(maxOperations(X, Y));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 implementation of the approach
# Function to return the maximum operations
# required to convert X to Y
def maxOperations(X, Y) :
# X cannot be converted to Y
if (X > Y) :
return -1;
diff = Y - X;
# If the difference is 1
if (diff == 1) :
return -1;
# If the difference is even
if (diff % 2 == 0) :
return (diff // 2);
# Add 3 to X and the new
# difference will be even
return (1 + ((diff - 3) // 2));
# Driver code
if __name__ == "__main__" :
X = 5; Y = 16;
print(maxOperations(X, Y));
# This code is contributed by AnkitRai01
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the maximum operations
// required to convert X to Y
static int maxOperations(int X, int Y)
{
// X cannot be converted to Y
if (X > Y)
return -1;
int diff = Y - X;
// If the difference is 1
if (diff == 1)
return -1;
// If the difference is even
if (diff % 2 == 0)
return (diff / 2);
// Add 3 to X and the new
// difference will be even
return (1 + ((diff - 3) / 2));
}
// Driver code
public static void Main(String []args)
{
int X = 5, Y = 16;
Console.WriteLine(maxOperations(X, Y));
}
}
// This code is contributed by PrinciRaj1992
Javascript
输出:
5
时间复杂度: O(1)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。