#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int MOD = 10000;
void mul(int a[][2], int b[][2])
{
int c[2][2] = {0};
for (int i = 0; i < 2; i ++ )
for (int j = 0; j < 2; j ++ )
for (int k = 0; k < 2; k ++ )
c[i][j] = (c[i][j] + a[i][k] * b[k][j]) % MOD;
memcpy(a, c, sizeof c);
}
int fib(int n)
{
int a[2][2] = {0, 1, 0, 0};//前两项是0,1;如果前两项是1,1则改成 {1, 1, 0, 0}
int f[2][2] = {0, 1, 1, 1};
while (n)
{
if (n & 1) mul(a, f);
mul(f, f);
n >>= 1;
}
return a[0][0];
}
int main()
{
int n;
while (cin >> n, n != -1)
cout << fib(n) << endl;
return 0;
}
矩阵乘法快速幂求斐波那契数列第n项
最新推荐文章于 2024-07-10 16:21:20 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)