- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 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
#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
Advertisements
To Continue Learning Please Login
Login with Google