假设我们有一个名为 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>usingnamespace 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);}