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

C++Server Side ProgrammingProgramming

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.


 Live Demo

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";
      cout << "No";
int main() {
   int a = 1, b = 7, c = 3;
   cout << "The answer is: ";
   isBInSequence(a, b, c);


The answer is: Yes
Published on 19-Dec-2019 12:38:58