hdu2256 Problem of precision(矩阵快速幂+推导)

题目链接https://vjudge.net/problem/HDU-2256

题目如下

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})^2的n次方,存在浮点数,不能直接取模,最好能把它转换为整型取模

推导如下

代码如下

#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
typedef long long ll;
const int mod=1024;
int n;
struct matrix
{
	ll s[2][2];
}base;
matrix operator*(matrix a,matrix b)
{
	matrix c;
	memset(c.s,0,sizeof(c.s));
	for(int i=0;i<2;i++)
		for(int j=0;j<2;j++)
		for(int k=0;k<2;k++)
		c.s[i][j]+=(a.s[i][k]%mod)*(b.s[k][j]%mod)%mod;
	return c;
}
ll pow_mod()
{
	matrix a;
	base.s[0][0]=5,base.s[0][1]=12,base.s[1][0]=2;
	base.s[1][1]=5;
	memset(a.s,0,sizeof(a.s));
	for(int i=0;i<2;i++)
		a.s[i][i]=1;
	int k=n-1;
	while(k)
	{
		if(k&1)a=a*base;
		base=base*base;
		k>>=1;
	}
	ll result;
	result=(5*a.s[0][0]+2*a.s[0][1])%mod;
	return (2*result-1)%mod;
}
int main()
{
	int t;
	cin>>t;
	while(t--)
	{
		cin>>n;
		ll ret;
		if(n==1)ret=9;
		else ret=pow_mod();
		cout<<ret<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41626975/article/details/82144936