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