天天看點

Fibonacci數

描述

無窮數列1,1,2,3,5,8,13,21,34,55...稱為fibonacci數列,它可以遞歸地定義為

f(n)=1 ...........(n=1或n=2)

f(n)=f(n-1)+f(n-2).....(n>2)

現要你來求第n個斐波納奇數。(第1個、第二個都為1)

輸入

第一行是一個整數m(m<5)表示共有m組測試資料

每次測試資料隻有一行,且隻有一個整形數n(n<20)

輸出

對每組輸入n,輸出第n個fibonacci數

樣例輸入

3

1

5

樣例輸出

2

#include <iostream>

using namespace std;

int main()

{

int m;

cin >> m; //n組測試資料

for (int test = 1; test <= m; test++)

int n;

cin >> n;

long long fn = 0,

f1 = 1,

f2 = 1;

for (int i = 3; i <= n; i++)

fn = f1 + f2;

f1 = f2;

f2 = fn;

}

if (fn != 0)

cout << fn << endl;

else

cout << 1 << endl;

return 0;