给定两个整数N和M ,任务是检查是否可以通过多次执行两个操作分别从X = 1和Y = 0获得这些值:
- 当且仅当x> 0时,将X和Y加1。
- 当且仅当y> 0时,将Y增加2。
例子:
Input: N = 3, M = 4
Output: Yes
Explanation:
Initially X = 1, Y = 0
Operation 1: X = 2, Y = 1
Operation 1: X = 3, Y = 2
Operation 2: X = 3, Y = 4, hence the final values are got so the answer is Yes.
Input: N = 5, M = 2
Output: No
Explanation :
Obtaining X = 5 and Y = 2 from X = 1 and Y = 0 is not possible.
方法:可以使用以下观察结果解决以上问题:
- 如果N小于2并且M不等于零,则不可能获得最终值,因此答案为No。
- 否则,从M减去N,如果M? 0并且M被2整除则答案是是。
- 在其他所有情况下,答案都是“否” 。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function that find given x and y
// is possible or not
bool is_possible(int x, int y)
{
// Check if x is less than 2 and
// y is not equal to 0
if (x < 2 && y != 0)
return false;
// Perform subtraction
y = y - x + 1;
// Check if y is divisible by 2
// and greater than equal to 0
if (y % 2 == 0 && y >= 0)
return true;
else
return false;
}
// Driver Code
int main()
{
// Given X and Y
int x = 5, y = 2;
// Function Call
if (is_possible(x, y))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
// Java program for the above approach
class GFG{
// Function that find given x and y
// is possible or not
static boolean is_possible(int x, int y)
{
// Check if x is less than 2 and
// y is not equal to 0
if (x < 2 && y != 0)
return false;
// Perform subtraction
y = y - x + 1;
// Check if y is divisible by 2
// and greater than equal to 0
if (y % 2 == 0 && y >= 0)
return true;
else
return false;
}
// Driver Code
public static void main(String[] args)
{
// Given X and Y
int x = 5, y = 2;
// Function Call
if (is_possible(x, y))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by rock_cool
Python3
# Python3 program for the above approach
# Function that find given x and y
# is possible or not
def is_possible(x, y):
# Check if x is less than 2 and
# y is not equal to 0
if (x < 2 and y != 0):
return false
# Perform subtraction
y = y - x + 1
# Check if y is divisible by 2
# and greater than equal to 0
if (y % 2 == 0 and y >= 0):
return True
else:
return False
# Driver Code
if __name__ == '__main__':
# Given X and Y
x = 5
y = 2
# Function Call
if (is_possible(x, y)):
print("Yes")
else:
print("No")
# This code is contributed by Mohit Kumar
C#
// C# program for the above approach
using System;
class GFG{
// Function that find given x and y
// is possible or not
static bool is_possible(int x, int y)
{
// Check if x is less than 2 and
// y is not equal to 0
if (x < 2 && y != 0)
return false;
// Perform subtraction
y = y - x + 1;
// Check if y is divisible by 2
// and greater than equal to 0
if (y % 2 == 0 && y >= 0)
return true;
else
return false;
}
// Driver Code
public static void Main(string[] args)
{
// Given X and Y
int x = 5, y = 2;
// Function Call
if (is_possible(x, y))
Console.Write("Yes");
else
Console.Write("No");
}
}
// This code is contributed by Ritik Bansal
Javascript
输出:
No
时间复杂度: O(1)
辅助空间: O(1)