POJ 3070 求解斐波那契第N項模P的餘數

2021-09-23 13:58:09 字數 1331 閱讀 7417

題意:

求解斐波那契第n項模p的餘數。

其中,n≤1000000000,p≤100000000

思路:

由斐波那契數列的性質可知,

f(1) = f(2) = 1;

n >= 3時

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

f(n - 1) = 1 * f(n - 1) + 0 * f(n - 2)

則有n>=3時,

[f(n)                  =        [1        1         *        [f(n - 1)

f(n - 1)]                         1      0]                   f(n - 2)]

=        [1        1 ^2         *        [f(n - 2)

1       0]                        f(n - 3)]

最終可以得到:

[f(n)                  =        [1        1 ^(n-2)       *        [f(2)

f(n - 1)]                         1      0]                           f(1)]

c++**如下:

// 求解斐波那契第n項模p的餘數。

// n≤1000000000,p≤100000000

// f(1) = f(2) = 1;

// n >= 3時

// f(n) = 1 * f(n - 1) + 1 * f(n - 2)

// f(n - 1) = 1 * f(n - 1) + 0 * f(n - 2)

#include #include #include using namespace std;

const int maxn = 100000005;

const int mod = 10000;

int n;

struct matrix

;matrix mul(matrix &x, matrix &y)

} return m;

}int pow(matrix x, int k)

return i.a[0][1];

}int main()

; while (cin >> k && k != -1)

return 0;

}

POJ3070 斐波那契數列 矩陣快速冪

題意就是讓你求斐波那契數列,不過n非常大,只能用logn的矩陣快速冪來做了 剛學完矩陣快速冪刷的水題,poj不能用萬能標頭檔案是真的煩 include include include include using namespace std typedef long long ll const int...

POJ 3070 矩陣快速冪求斐波那契數列

方法一 矩陣快速冪取模求斐波那契數列 include include define maxn 10000 using namespace std struct matrix m matrix mul matrix a,matrix b matrix mtpow matrix a,int k int ...

POJ3070 斐波那契數列遞推 矩陣快速冪模板題

題目分析 對於給出的n,求出斐波那契數列第n項的最後4為數,當n很大的時候,普通的遞推會超時,這裡介紹用矩陣快速冪解決當遞推次數很大時的結果,這裡矩陣已經給出,直接計算即可 1 include2 include3 using namespace std 45 const int mod 10000 ...