HDU 2256 Problem of Precision(矩阵快速幂入门题)

Problem Description

 

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
 

Source
         这道题目是求((sqrt(2)+sqrt(3))^2n)mod1024向下取整,需要推到一下····
 分析:

所以可以用矩阵快速幂很快的求出来,又因为(5+2*sqrt(6))^n+(5-2*sqrt(6))^n=An+Bn*sqrt(6)+An-Bn*sqrt(6)=2An,由于(5-2*sqrt(6))^n是一个趋于0的数·····
由于精度向下取整所以最后的结果就是(5+2*sqrt(6))^n=2An-1;
代码如下:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define Max_dimension 2
#define mod 1024

typedef int Matrix_type;
typedef _int64 Max_int_type;
typedef Matrix_type Matrix[Max_dimension][Max_dimension];

int ndim=2;
Matrix res;
void m_zero(Matrix x)
{
	memset(x,0,sizeof(Matrix_type)*Max_dimension*Max_dimension);
}

void m_one(Matrix x)
{
	m_zero(x);
	for(int i=0;i<ndim;i++)
		x[i][i]=1;
}

void m_copy(Matrix src,Matrix dest)
{
	memcpy(dest,src,sizeof(Matrix_type)*Max_dimension*Max_dimension);
}


//c=a*b
void m_multiple(Matrix  a,Matrix b,Matrix c)
{
	int i,j,k;

	for(i=0;i<ndim;i++)
		for(j=0;j<ndim;j++)
		{
			c[i][j]=0;
			for(k=0;k<ndim;k++)
			{
				c[i][j]+=(a[i][k]*b[k][j])%mod;
				c[i][j]%=mod;
			}
		}
}

//y=x^n
void m_pow(Matrix x, unsigned int n, Matrix y)
{
	Matrix temp,temp_x;
	m_one(y);
	m_copy(x,temp_x);
	while(n)
	{
		if (n&1)
		{
			m_multiple(temp_x,y,temp);
			m_copy(temp,y);
		}
		if (n >>= 1)
		{
			m_multiple(temp_x,temp_x,temp);
			m_copy(temp,temp_x);
		}
	}
}

int main()
{
	//freopen("in.txt","r",stdin);
	int T,m;
	scanf("%d",&T);
	Matrix ans;
	res[0][0]=5;
	res[0][1]=12;
	res[1][0]=2;
	res[1][1]=5;

	while(T--)
	{
		scanf("%d",&m);
		if(m==0)
		{
			printf("1\n");
			continue;
		}
		if(m==1)
		{
			printf("9\n");
			continue;
		}

		m_pow(res,m-1,ans);//算出An-1,Bn-1

		int num=ans[0][0]*5+ans[1][0]*12;
		printf("%d\n",(num*2-1)%mod);
	}
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值