Find if a number is part of AP whose first element and difference are given
Last Updated :
20 Nov, 2023
Given three non-negative integers a, d and x. Here, a is the first element, d is the difference of an AP (Arithmetic Progression). We need to find if x is part of the given AP or not.
Examples :
Input : a = 1, d = 3, x = 7
Output : Yes
7 is part of given AP, 1 + 3 + 3 = 7
Input : a = 10, d = 0, x = 10
Output : Yes
Firstly, in case d = 0, we should output Yes if a = x else answer is No. For non-zero d, if x belongs to sequence x = a + n * d where n is non-negative integer, only if (x – a) / d is non-negative integer.
C++
#include <bits/stdc++.h>
using namespace std;
bool isMember( int a, int d, int x)
{
if (d == 0)
return (x == a);
return ((x - a) % d == 0 && (x - a) / d >= 0);
}
int main()
{
int a = 1, x = 7, d = 3;
if (isMember(a, d, x))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
class GFG {
static boolean isMember( int a, int d, int x)
{
if (d == 0 )
return (x == a);
return ((x - a) % d == 0 && (x - a) / d >= 0 );
}
public static void main(String args[])
{
int a = 1 , x = 7 , d = 3 ;
if (isMember(a, d, x))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def isMember(a, d, x):
if d = = 0 :
return x = = a
return ((x - a) % d = = 0 and
int ((x - a) / d) > = 0 )
a = 1
x = 7
d = 3
if isMember(a, d, x):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG {
static bool isMember( int a, int d, int x)
{
if (d == 0)
return (x == a);
return ((x - a) % d == 0 && (x - a) / d >= 0);
}
public static void Main()
{
int a = 1, x = 7, d = 3;
if (isMember(a, d, x))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
function isMember(a, d, x)
{
if (d == 0)
return (x == a);
return ((x - a) % d == 0 && (x - a) / d >= 0);
}
let a = 1, x = 7, d = 3;
if (isMember(a, d, x))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
PHP
<?php
function isMember( $a , $d , $x )
{
if ( $d == 0)
return ( $x == $a );
return (( $x - $a ) % $d == 0 &&
( $x - $a ) / $d >= 0);
}
$a = 1; $x = 7; $d = 3;
if (isMember( $a , $d , $x ))
echo "Yes" ;
else
echo "No" ;
?>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...