Check if it is possible to move from (a, 0) to (b, 0) with given jumps
Last Updated :
17 Apr, 2023
Given two points, i.e. (a, 0) to (b, 0). The task is to check whether it is possible to move from (a,0) to (b,0) or not. One can move as (a, 0), (a+x, 0), (a+x+1, 0), (a, 2*x, 0), (a, 2*x+1, 0)……
Examples:
Input: a = 3, x = 10, b = 4
Output: No
Input: a = 3, x = 2, b = 5
Output: Yes
Approach: An answer will be possible if:
- a + n*x = b, where n is a non-negative integer.
- a + n*x + 1 = b where n is a positive integer.
So,
(b – a) / x is an integer or (b – a – 1) / x is an integer
(b – a) % x = 0 or (b – a – 1) % x = 0
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool Move( int a, int x, int b)
{
if ((((b - a) % x == 0) || ((b - a - 1) % x == 0) && a + 1 != b) && b >= a)
return true ;
return false ;
}
int main()
{
int a = 3, x = 2, b = 7;
if (Move(a, x, b))
cout << "Yes" ;
else
cout << "No" ;
}
|
C
#include <stdio.h>
#include <stdbool.h>
bool Move( int a, int x, int b)
{
if ((((b - a) % x == 0) || ((b - a - 1) % x == 0) && a + 1 != b) && b >= a)
return true ;
return false ;
}
int main()
{
int a = 3, x = 2, b = 7;
if (Move(a, x, b))
printf ( "Yes" );
else
printf ( "No" );
}
|
Java
import java.io.*;
class GFG {
static boolean Move( int a, int x, int b)
{
if ((((b - a) % x == 0 ) || ((b - a - 1 ) % x == 0 ) && a + 1 != b) && b >= a)
return true ;
return false ;
}
public static void main (String[] args) {
int a = 3 , x = 2 , b = 7 ;
if (Move(a, x, b))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python 3
def Move(a, x, b):
if ((((b - a) % x = = 0 ) or
((b - a - 1 ) % x = = 0 ) and
a + 1 ! = b) and b > = a):
return True
return False
if __name__ = = "__main__" :
a = 3
x = 2
b = 7
if (Move(a, x, b)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG
{
static bool Move( int a, int x, int b)
{
if ((((b - a) % x == 0) ||
((b - a - 1) % x == 0) &&
a + 1 != b) && b >= a)
return true ;
return false ;
}
public static void Main ()
{
int a = 3, x = 2, b = 7;
if (Move(a, x, b))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
PHP
<?php
function Move( $a , $x , $b )
{
if (((( $b - $a ) % $x == 0) ||
(( $b - $a - 1) % $x == 0) &&
$a + 1 != $b ) && $b >= $a )
return true;
return false;
}
$a = 3; $x = 2; $b = 7;
if (Move( $a , $x , $b ))
echo "Yes" ;
else
echo "No" ;
?>
|
Javascript
<script>
function Move(a,x,b)
{
if ((((b - a) % x == 0) || ((b - a - 1) % x == 0)
&& a + 1 != b) && b >= a)
return true ;
return false ;
}
let a = 3, x = 2, b = 7;
if (Move(a, x, b))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...