51nod 巨大的斐波那契数列(矩阵快速幂),递推式优化的好模板!!!!!!!

本文介绍了一种使用矩阵快速幂算法高效计算斐波那契数列第n项的方法,该方法适用于大整数计算场景,避免了传统递归方式的效率瓶颈。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


斐波那契数列的定义如下:

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

著作权归作者所有。
商业转载请联系作者获得授权,非商业转载请注明出处。
作者:王希
链接:http://www.zhihu.com/question/23582123/answer/40464211
来源:知乎

矩阵递推关系

学过代数的人可以看出,下面这个式子是成立的:
&amp;lt;img src=&quot;https://i-blog.csdnimg.cn/blog_migrate/202c202d7ff7b6e11c1b3436fd789ad5.png&quot; data-rawwidth=&quot;284&quot; data-rawheight=&quot;69&quot; class=&quot;content_image&quot; width=&quot;284&quot;&amp;gt;不停地利用这个式子迭代右边的列向量,会得到下面的式子: 不停地利用这个式子迭代右边的列向量,会得到下面的式子:
&amp;lt;img src=&quot;https://i-blog.csdnimg.cn/blog_migrate/4f08da760eb450bde73ad90c04d98f30.png&quot; data-rawwidth=&quot;270&quot; data-rawheight=&quot;70&quot; class=&quot;content_image&quot; width=&quot;270&quot;&amp;gt;这样,问题就转化为如何计算这个矩阵的n次方了,可以采用快速幂的方法。 这样,问题就转化为如何计算这个矩阵的n次方了,可以采用快速幂的方法。 快速幂_百度百科是利用结合律快速计算幂次的方法。比如我要计算 2^{20} ,我们知道 2^{20} =  2^{16} * 2^{4}  ,而 2^{2} 可以通过 2^{1} \times 2^{1} 来计算, 2^{4} 而可以通过 2^{2}\times 2^{2}  计算,以此类推。通过这种方法,可以在O(lbn)的时间里计算出一个数的n次幂。快速幂的代码如下:




#include <iostream>
#include <algorithm>
#include <cmath>
#define MOD 1000000009
#define N 2
using namespace std;

struct Matrix 
{
	long long v[N][N];
};

Matrix matrix_mul(Matrix A, Matrix B, long long m)
{
	Matrix ans;

	for (int i = 0; i < N; i++)
	{
		for (int j = 0; j < N; j++)
		{
			ans.v[i][j] = 0;
			for (int k = 0; k < N; k ++)
			{
				ans.v[i][j] += (A.v[i][k] * B.v[k][j]) % m;
			}
			ans.v[i][j] %= m;
		}
	}
	return ans;
}

Matrix matrix_pow(Matrix C, long long n, long long m)
{
	Matrix ans = {1, 0, 0, 1};
	while (n)
	{
		if (n & 1)
			ans = matrix_mul(ans, C, m);
		C = matrix_mul(C, C, m);
		n >>= 1;
	}
	return ans;
}

int main()
{
	long long n;
	Matrix temp1 = {1, 1, 1, 0}, temp2 = {1, 0, 1, 0}; // temp2{f[2],0,f[1],0}!!!!!
	while (cin >> n)
	{
		if (n < 2)
		{
			cout << 1 << endl;
			continue;
		}
		Matrix res = matrix_pow(temp1, n - 2, MOD);
		res = matrix_mul(res, temp2, MOD);
		cout << res.v[0][0] << endl;
	}
	return 0;
}





评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值