Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
#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
Advertisements
