- 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 the Nth term of the series where each term f[i] = f[i β 1] β f[i β 2] in C++
Suppose we have a series called f. Each term of f, follows this rule f[i] = f[i – 1] – f[i – 2], we have to find the Nth term of this sequence. f[0] = X and f[1] = Y. If X = 2 and Y = 3, and N = 3. The result will be -2.
If we see this closely, there will be almost six terms before the sequence starts repeating itself. So we will find the first 6 terms of the series and then the Nth term will be the same as (N mod 6)th term.
Example
#include< iostream> using namespace std; int searchNthTerm(int x, int y, int n) { int terms[6]; terms[0] = x; terms[1] = y; for (int i = 2; i < = 5; i++) terms[i] = terms[i - 1] - terms[i - 2]; return terms[n % 6]; } int main() { int x = 2, y = 3, n = 3; cout << "Term at index " < < n << " is: "<< searchNthTerm(x, y, n); }
Output
Term at index 3 is: -2
Advertisements