Find if the given number is present in the infinite sequence or not in C++

Suppose we have three integers a, b and c. Suppose in an infinite sequence, a is the first term, and c is a common difference. We have to check whether b is present in the sequence or not. Suppose the values are like a = 1, b = 7 and c = 3, Then the sequence will be 1, 4, 7, 10, …, so 7 is present in the sequence, so the output will be ‘yes’.

To solve this problem, we have to follow these two steps −

• When c = 0, and a = b, then print yes, and if a is not same as b, then return no

• When c > 0, then for any non-negative integer k, the equation will be b = a + k*c must be satisfied. So (b-a)/c will be a non-negative integer.

Example

Live Demo

#include<iostream>
using namespace std;
void isBInSequence(int a, int b, int c){
if (a == b)
cout << "Yes";
if ((b - a) * c > 0 && (b - a) % c == 0)
cout << "Yes";
else
cout << "No";
}
int main() {
int a = 1, b = 7, c = 3;
cout << "The answer is: ";
isBInSequence(a, b, c);
}

Output

The answer is: Yes