nyoj 148 fibonacci数列(二)

题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=148

/

题目的意思就是给个数n求fibonacci数列的第n项mod10000的结果,

显然要用到矩阵连乘,因为题中已经给出了解题思路,这里就不多说了,主要是算矩阵幂的时候用快速幂,


参考代码如下:

#include <iostream>
using namespace std;
class mat
{
public:
	int m[2][2];
};
int mod;
mat operator*(mat a,mat b)
{
    int i,j,k;
    mat c;
    for (i=0;i<2;i++)
    {
        for (j=0;j<2;j++)
        {
            c.m[i][j] = 0;
            	for (k=0;k<2;k++)
                	c.m[i][j]+=(a.m[i][k]*b.m[k][j])%mod;
           	    c.m[i][j]%=mod;
        }
    }
    return c;
}
mat operator^(mat a,int x)  
{  
     mat p = a,q = a;
	 x--;
     while (x>=1)  
     {  
         if(x%2==1)  
             p = p*q;  
         x/=2;  
         q = q*q;  
     }  
     return p;  
}
int main()
{
	int n;
	mod=10000;
	while(cin>>n&&n!=-1)
	{
		if(n==0)
		{
			cout<<0<<endl;
			continue;
		}
		if(n==1||n==2)
		{
			cout<<1<<endl;
			continue;
		}
		mat c;
		mat a;
		a.m[0][0]=a.m[0][1]=a.m[1][0]=1;
		a.m[1][1]=0;
		c=a^(n-2);
		int ans=(c.m[0][0]+c.m[1][0])%10000;
		cout<<ans<<endl;

	}
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值