HDU 1588(Gauss Fibonacci)

#include <iostream>
using namespace std;
const int len = 2;

struct Node
{
	__int64 mat[2][2];
};

Node unit, A; //单位矩阵,矩阵A
int k, b, n, M;

//计算(a*b)%M,其中a和b都是矩阵,M是正整数
Node mul(const Node& a, const Node& b)
{
	Node c;
	for (int i = 0; i < len; i++)
	{
		for (int j = 0; j < len; j++)
		{
			c.mat[i][j] = 0;
			for (int k = 0; k < len; k++)
			{
				c.mat[i][j] += (a.mat[i][k] * b.mat[k][j]) % M;
			}
			c.mat[i][j] %= M;
		}
	}
	return c;
}

//计算a^x,其中a是矩阵,x是非负整数
Node power(const Node& a, int x)
{
	int t = x, d = 0;
	while (t)
	{
		++d;
		t >>= 1;
	}
	Node res = unit;
	for (int i = d; i > 0; i--)
	{
		res = mul(res, res);
		if (x & (1 << (i - 1)))
		{
			res = mul(res, a);
		}
	}
	return res;
}

//计算(a+b)%M,其中a和b都是矩阵,M是正整数
Node add(const Node& a, const Node& b)
{
	Node c;
	for (int i = 0; i < len; i++)
	{
		for (int j = 0; j < len; j++)
		{
			c.mat[i][j] = (a.mat[i][j] + b.mat[i][j]) % M;
		}
	}
	return c;
}

//计算a+a^2+...+a^x,其中a是矩阵,x是正整数
Node sum(const Node& a, int x)
{
	if (x == 1)
	{
		return a;
	}
	Node temp = sum(a, x >> 1);
	if (x & 1)
	{
		Node tmp = power(a, (x >> 1) + 1);
		return add(add(mul(temp, tmp), temp), tmp);
	}
	else
	{
		Node tmp = power(a, (x >> 1));
		return add(mul(tmp, temp), temp);
	}
}

int main()
{
	unit.mat[0][0] = unit.mat[1][1] = 1; unit.mat[0][1] = unit.mat[1][0] = 0;
	A.mat[0][0] = 1; A.mat[0][1] = 1; A.mat[1][0] = 1; A.mat[1][1] = 0;
	while (cin >> k >> b >> n >> M)
	{
		Node res;
		res = power(A, k);
		res = sum(res, n - 1);
		res = add(res, unit);
		Node ans = power(A, b);
		res = mul(ans, res);
		cout << res.mat[1][0] << endl;
	}
	return 0;
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值