求斐波那契數列的第n項

2022-05-01 22:57:25 字數 1518 閱讀 3080

斐波那契數列的定義如下:

f(0) = 0

f(1) = 1

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

(1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, ...)

給出n,求f(n),由於結果很大,輸出f(n) % 1000000009的結果即可。

input

輸入1個數n(1 <= n <= 10^18)。
output

輸出f(n) % 1000000009的結果。
input示例

11
output示例

89

因為十分的大,如果用陣列來儲存,肯定會時間超限,因此用矩陣快速冪可以很好的解決。

矩陣快速冪與快速冪類似,都是通過不斷二分減少計算次數來實現目標。只不過矩陣快速冪通過轉移方程將具有一般通式的方程轉化為冪級來計數,就比方這個斐波那契數列的第n項。

#include #include 

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

using

namespace

std;

#pragma comment(linker, "/stck:1024000000,1024000000")

#define lowbit(x) (x&(-x))

#define max(x,y) (x>=y?x:y)

#define min(x,y) (x<=y?x:y)

#define max 100000000000000000

#define mod 1000000009

#define pi acos(-1.0)

#define ei exp(1)

#define pi 3.1415926535897932384626433832

#define ios() ios::sync_with_stdio(true)

#define inf 1044266558

#define mem(a) (memset(a,0,sizeof(a)))typedef

long

long

ll;//

矩陣快速冪

struct

matrix

;matrix matrix_multiply(matrix x,matrix y)

void

matrix_pow(ll n)

printf(

"%lld

",ans.a[0][1

]);}

intmain()

求斐波那契數列的第n項

問題描述 斐波那契數列是這樣的乙個數列,1,1,2,3,5,8,即前兩項都是1,後面每一項都是其前面兩項的和。現在要你求出該數列的第n項。解法一 遞迴演算法。很多教科書上都用這個題作為函式遞迴知識點講解的例題,我們可以將每乙個項的求法表達為這樣乙個式子 f n f n 1 f n 2 f 1 1,f...

斐波那契數列第n項

1 斐波那契數列第n項 在斐波那契數列中,fib0 0,fib1 1,fibn fibn 1 fibn 2 n 1 給定整數n,求fibn mod10000。輸入格式 輸入包含多組測試用例。每個測試用例佔一行,包含乙個整數n。當輸入用例n 1時,表示輸入終止,且該用例無需處理。輸出格式 每個測試用例...

求斐波那契數列第n項的值

斐波那契數列的描述 斐波那契數列的描述 斐波那契數列,又稱 分割數列,指的是這樣的乙個數列 0 1 1 2 3 5 8 13 21 在數學上,斐波那契數列定義如下 f 0 0,f 1 1,f n f n 1 f n 2 n 2,n n 即這個數列從第二項開始,每一項都等於前兩項之和。特別指出 0是第...