假設我們有一個名為 f 的序列。f 的每一項都遵循此規則 f[i] = f[i – 1] – f[i – 2],我們必須找到此序列的第 N 項。f[0] = X 且 f[1] = Y。如果 X = 2 且 Y = 3,並且 N = 3。結果將為 -2。
如果我們仔細觀察,在序列開始重複自身之前,將會有大約六項。因此,我們將找到該序列的前 6 項,然後第 N 項將與第 (N mod 6) 項相同。
示例
#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);
}