在C ++中找到每个项f [i] = f [i – 1] – f [i – 2]的级数的第N个项
假设我们有一个叫做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个术语与第(Nmod6)个术语相同。
示例
#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