POJ 3070 Fibonacci

矩阵快速幂求fibonacci数。

思路:因为上次周赛遇到一道求fibonacci的变形题,那个数与fibonacci的关系都推出来了,但是由于数据量有1000,各种超unsigned long long ,一直TLE,所以今天从师兄给我的矩阵资料上找到矩阵快速幂求fibonacci数的资料。待会同学过生日去吃饭,回来再写写总结。

这篇文章写的蛮不错的:http://www.cnblogs.com/Knuth/archive/2009/09/04/1559951.html

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;

const int MOD = 10000;

int n;

void Mul(int d[][2], int a[][2], int b[][2], int n)
{
	int c[2][2];
	memset(c, 0, sizeof(c));
	for(int i = 0; i < n; i++)
	{
		for(int j = 0; j < n; j++)
		{
			int tot = 0;
			for(int k = 0; k < n; k++)
			{
				tot += a[i][k] * b[k][j];
				if(tot >= MOD) tot %= MOD;
			}
			c[i][j] = tot;
		}
	}
	for(int i = 0; i < 2; i++)
	{
		for(int j = 0; j < 2; j++)
		{
			d[i][j] = c[i][j];
		}
	}
}

int cal(int n)
{
	int t[2][2] = {{0, 1}, {0, 1}};
	int a[2][2] = {{0, 1}, {1, 1}};
	while(n)
	{
		if(n & 1) Mul(t, t, a, 2);
		Mul(a, a, a, 2);
		n /= 2;
	}
	return t[0][0];
}

int read_case()
{
	scanf("%d", &n);
	if(n == -1) return 0;
	return 1;
}

void solve()
{
	if(!n) { printf("0\n"); return ;}
	int ans = cal(n);
	printf("%d\n", ans);
}

int main()
{
	while(read_case())
	{
		solve();
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值