สมมุติว่าเรามีชุดชื่อ 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);
} ผลลัพธ์
Term at index 3 is: -2