Given three integers A, B and C. In an infinite sequence, A is the first number, C is the common difference (Si – Si – 1 = C). The task is to check if the number B will appear in the sequence or not.
Examples:
Input: A = 1, B = 7, C = 3
Output: Yes
The sequence will be 1, 4, 7, 10, …
Input: A = 1, B = -4, C = 5
Output: No
Approach: There are two cases:
- When C = 0, print Yes if A = B else No as the sequence will consist only the number A
- When C > 0, for any non-negative integer k the equation B = A + k * C must be satisfied i.e. (B – A) / C must be a non-negative integer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool doesContainB( int a, int b, int c)
{
if (a == b)
return true ;
if ((b - a) * c > 0 && (b - a) % c == 0)
return true ;
return false ;
}
int main()
{
int a = 1, b = 7, c = 3;
if (doesContainB(a, b, c))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
class GFG
{
static boolean doesContainB( int a, int b, int c)
{
if (a == b)
{
return true ;
}
if ((b - a) * c > 0 && (b - a) % c == 0 )
{
return true ;
}
return false ;
}
public static void main(String[] args)
{
int a = 1 , b = 7 , c = 3 ;
if (doesContainB(a, b, c))
{
System.out.println( "Yes" );
}
else
{
System.out.println( "No" );
}
}
}
|
Python3
def doesContainB(a, b, c):
if (a = = b):
return True
if ((b - a) * c > 0 and (b - a) % c = = 0 ):
return True
return False
if __name__ = = '__main__' :
a, b, c = 1 , 7 , 3
if (doesContainB(a, b, c)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG
{
static bool doesContainB( int a, int b, int c)
{
if (a == b)
{
return true ;
}
if ((b - a) * c > 0 && (b - a) % c == 0)
{
return true ;
}
return false ;
}
public static void Main()
{
int a = 1, b = 7, c = 3;
if (doesContainB(a, b, c))
{
Console.WriteLine( "Yes" );
}
else
{
Console.WriteLine( "No" );
}
}
}
|
PHP
<?php
function doesContainB( $a , $b , $c )
{
if ( $a == $b )
return true;
if (( $b - $a ) * $c > 0 &&
( $b - $a ) % $c == 0)
return true;
return false;
}
$a = 1; $b = 7; $c = 3;
if (doesContainB( $a , $b , $c ))
echo "Yes" ;
else
echo "No" ;
?>
|
Javascript
<script>
function doesContainB(a, b, c)
{
if (a == b)
{
return true ;
}
if ((b - a) * c > 0 && (b - a) % c == 0)
{
return true ;
}
return false ;
}
let a = 1, b = 7, c = 3;
if (doesContainB(a, b, c))
{
document.write( "Yes" );
}
else
{
document.write( "No" );
}
</script>
|
Time Complexity: O(1), since there is only basic arithmetic which takes constant time.
Auxiliary Space: O(1), since no extra space has been taken.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!