Find if a number is part of AP whose first element and difference are given using C++.


Suppose we have the first element of AP, and the differenced. We have to check whether the given number n is a part of AP or not. If the first term is a = 1, differenced = 3, and the term x = 7 will be checked. The answer is yes.

To solve this problem, we will follow these steps −

  • If d is 0, and a = x, then return true, otherwise false.
  • Otherwise, if d is not 0, then if x belongs to the sequence x = a + n * d, where n is a non-negative integer, only if (n - a)/c is a non-negative integer.

Example

 Live Demo

#include <iostream>
using namespace std;
bool isInAP(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 (isInAP(a, d, x))
      cout << "The value " << x << " is present in the AP";
   else
      cout << "The value " << x << "is not present in the AP";
}

Output

The value 7 is present in the AP

Updated on: 30-Oct-2019

447 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements