HDU-2256(矩阵快速幂)

本文介绍了一种使用矩阵快速幂解决特定数学问题的方法。通过定义矩阵运算和递归公式,可以高效地计算出形如{[sqrt(2)+sqrt(3)]^2n}

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

 
Input
The first line of input gives the number of cases, T. T test cases follow, each on a separate line. Each test case contains one positive integer n. (1 <= n <= 10^9) 
Output
For each input case, you should output the answer in one line. 
Sample Input
3
1
2
5
Sample Output
9
97
841


/*
题意:
求{[sqrt(2)+sqrt(3)]^2n}%1024取整

题解:
见上图

*/

#include <stdio.h>
#include <string.h>
#include<iostream>
#include <algorithm>
using namespace std;
#define LL __int64
struct node
{
	LL maxtri[6][6];
};
node res, roi;
LL n, kk = 1024;


node operator * (node &a, node &b)
{
	node ans;
		for (int i = 0; i < 2; i++)
		{
			for (int j = 0; j < 2; j++)
			{
				ans.maxtri[i][j] = 0;
				for (int k = 0; k < 2; k++)
				{
					ans.maxtri[i][j] += a.maxtri[i][k] * (b.maxtri[k][j]%kk)%kk;
					ans.maxtri[i][j] %= kk;
				}
			}
		}
	return ans;
}


void quickmuti(LL nn)
{
	node temp;
	for (int i = 0; i < 2; i++)
	{
		for (int j = 0; j < 2; j++)
		{
			temp.maxtri[i][j] = (i == j);
		}
	}
	while (nn)
	{
		if (nn & 1)
		{
			temp = temp*roi;
		}
		nn >>= 1;
		roi = roi*roi;
	}
	res = temp;
}

void init()
{
	memset(roi.maxtri, 0, sizeof(roi.maxtri));
	memset(res.maxtri, 0, sizeof(res.maxtri));
	roi.maxtri[0][0] = roi.maxtri[1][1] = 5;
	roi.maxtri[1][0] = 2;
	roi.maxtri[0][1] = 12;
	res.maxtri[0][0] = 5;
	res.maxtri[1][0] = 2;
}

int main()
{
	int t;
	cin >> t;
	while (t--)
	{
		scanf("%I64d", &n);
		int num[3] = { 1,1,2 };
		if (n == 1)
		{
			cout << '9' << endl;
			continue;
		}
		init();
		quickmuti(n-1);
		LL ans = 0;
		ans = (LL)(res.maxtri[0][0]*5 + 2*res.maxtri[0][1])%kk;
		
		printf("%I64d\n", (2*ans-1)%kk);
	}

	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值