
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find If a Number is Part of an AP 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