矩阵快速幂求斐波拉契数列的第n项


代码:

#include <cstdio>
#include <cstring>
#define MOD 1000000007
#define LL long long
#define N 10

struct node
{
	int mat[N][N];
};

int n;
node xx;

node mul(node a, node b)
{
	node c;
	memset(c.mat, 0, sizeof(c.mat));
	for(int i= 0; i< n; i++)
		for(int j= 0; j< n; j++)
			for(int k= 0; k< n; k++)
				c.mat[i][j]+= a.mat[i][k]* b.mat[k][j];
	return c;			
}


node fun(node a, int b)
{
	node ans= xx;
	node t= a;
	while(b)
	{
		if(b&1)
			ans=mul(ans, t);
		t= mul(t, t);
		b/= 2;	
	}
	return ans;
}

int main()
{
	memset(xx.mat, 0, sizeof(xx.mat));
	for(int i= 0; i< N; i++)
		xx.mat[i][i]= 1;
	node a;
	int b;
	while(scanf("%d %d",&n,&b)!=EOF)
	{
		for(int i= 0; i< n; i++)
			for(int j= 0; j< n; j++)
				scanf("%d",&a.mat[i][j]);
		node ans= fun(a, b);
		for(int i= 0; i< n; i++)
		{
			for(int j= 0; j< n; j++)
				printf("%d ",ans.mat[i][j]);
			printf("\n");	
		}			
	}
	return 0;	
}

POJ 3070

代码:

#include <cstdio>
#include <cstring>
#define MOD 10000
#define LL long long
#define N 10

struct node
{
	int mat[N][N];
};

int n;
node xx;

node mul(node a, node b)
{
	node c;
	memset(c.mat, 0, sizeof(c.mat));
	for(int i= 0; i< n; i++)
		for(int j= 0; j< n; j++)
			for(int k= 0; k< n; k++)
				c.mat[i][j]= (c.mat[i][j]+ a.mat[i][k]* b.mat[k][j])%MOD;
	return c;			
}


node fun(node a, int b)
{
	node ans= xx;
	node t= a;
	while(b)
	{
		if(b&1)
			ans=mul(ans, t);
		t= mul(t, t);
		b/= 2;	
	}
	return ans;
}

int main()
{
	memset(xx.mat, 0, sizeof(xx.mat));
	for(int i= 0; i< N; i++)
		xx.mat[i][i]= 1;
	node a;
	int b;
	a.mat[0][0]= a.mat[0][1]= a.mat[1][0]= 1;
	a.mat[1][1]= 0;
	n= 2; 
	while(scanf("%d",&b)!=EOF && b!=-1)
	{
		if(b== 0)
		{
			printf("0\n");
			continue;
		}
		if(b== 1 || b== 2)
		{
			printf("1\n");
			continue;
		}
		node ans= fun(a, b-2);
		printf("%d\n",(ans.mat[0][0] + ans.mat[0][1])%MOD);
	}			
	return 0;	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值