Is it possible to reach N and M from 1 and 0 respectively as per given condition
Last Updated :
04 Aug, 2021
Given two integers N and M, the task is to check if it is possible to obtain these values from X = 1 and Y = 0 respectively by performing the two operations any number of times::
- Increase X and Y by 1, if and only if x>0.
- Increase Y by 2, if and only if y>0.
Examples:
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.
Approach: The above problem can be solved using the below observations:
- If N is less than 2 and M is not equal to zero, then getting the final values is not possible, hence the answer is No.
- Otherwise, subtract N from M and if M ? 0 and M is divisible by 2 then the answer is Yes.
- In all other cases, the answer is No.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool is_possible( int x, int y)
{
if (x < 2 && y != 0)
return false ;
y = y - x + 1;
if (y % 2 == 0 && y >= 0)
return true ;
else
return false ;
}
int main()
{
int x = 5, y = 2;
if (is_possible(x, y))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
class GFG{
static boolean is_possible( int x, int y)
{
if (x < 2 && y != 0 )
return false ;
y = y - x + 1 ;
if (y % 2 == 0 && y >= 0 )
return true ;
else
return false ;
}
public static void main(String[] args)
{
int x = 5 , y = 2 ;
if (is_possible(x, y))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def is_possible(x, y):
if (x < 2 and y ! = 0 ):
return false
y = y - x + 1
if (y % 2 = = 0 and y > = 0 ):
return True
else :
return False
if __name__ = = '__main__' :
x = 5
y = 2
if (is_possible(x, y)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG{
static bool is_possible( int x, int y)
{
if (x < 2 && y != 0)
return false ;
y = y - x + 1;
if (y % 2 == 0 && y >= 0)
return true ;
else
return false ;
}
public static void Main( string [] args)
{
int x = 5, y = 2;
if (is_possible(x, y))
Console.Write( "Yes" );
else
Console.Write( "No" );
}
}
|
Javascript
<script>
function is_possible(x, y)
{
if (x < 2 && y != 0)
return false ;
y = y - x + 1;
if (y % 2 == 0 && y >= 0)
return true ;
else
return false ;
}
let x = 5, y = 2;
if (is_possible(x, y))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...