HDU——4549M斐波那契数列(矩阵快速幂+快速幂+费马小定理)

M斐波那契数列

Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others)
Total Submission(s): 2598    Accepted Submission(s): 774


Problem Description
M斐波那契数列F[n]是一种整数数列,它的定义如下:

F[0] = a
F[1] = b
F[n] = F[n-1] * F[n-2] ( n > 1 )

现在给出a, b, n,你能求出F[n]的值吗?
 

Input
输入包含多组测试数据;
每组数据占一行,包含3个整数a, b, n( 0 <= a, b, n <= 10^9 )
 

Output
对每组测试数据请输出一个整数F[n],由于F[n]可能很大,你只需输出F[n]对1000000007取模后的值即可,每组数据输出一行。
 

Sample Input
0 1 0 6 10 2
 

Sample Output
0 60
 

水题一道
代码:
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<sstream>
#include<cstring>
#include<cstdio>
#include<string>
#include<deque>
#include<stack>
#include<cmath>
#include<queue>
#include<set>
#include<map>
using namespace std;
#define INF 0x3f3f3f3f
#define MM(x) memset(x,0,sizeof(x))
#define MMINF(x) memset(x,INF,sizeof(x))
typedef long long LL;
const double PI=acos(-1.0);
const LL mod=1000000007;
struct mat
{
	LL pos[2][2];
	mat(){MM(pos);}
};
mat operator*(const mat &a,const mat &b)
{
	mat c;
	for (int i=0; i<2; i++)
	{
		for (int j=0; j<2; j++)
		{
			for (int k=0; k<2; k++)
			c.pos[i][j]+=(a.pos[i][k]*b.pos[k][j])%(mod-1);
		}
	}
	return c;
}
mat operator^(mat a,LL b)
{
	mat r;
	for (int i=0; i<2; i++)
		r.pos[i][i]=1;
	while (b!=0)
	{
		if(b&1)
			r=r*a;
		a=a*a;
		b>>=1;
	}
	return r;
}
LL qpow(LL a,LL b)
{
	LL r=1;
	a%=mod;
	while (b)
	{
		if(b&1)
			r=(r*a)%mod;
		a=(a*a)%mod;
		b>>=1;
	}
	return r;
}
int main(void)
{
	LL pa,pb;
	LL a,b,c,n;
	while (~scanf("%I64d%I64d%I64d",&a,&b,&n))
	{
		if(n==0)
			printf("%I64d
",a);
		else if(n==1)
			printf("%I64d
",b);
		else
		{
			mat t,one;
			t.pos[0][0]=1;
			t.pos[0][1]=1;
			t.pos[1][0]=1;
			one.pos[0][0]=1;
			one.pos[1][0]=1;
			t=t^(n-2);
			one=t*one;
			pa=one.pos[1][0]%(mod-1);
			pb=one.pos[0][0]%(mod-1);
			printf("%I64d
",(qpow(a,pa)*qpow(b,pb))%mod);
		}	
	}
	return 0;
}
原文地址:https://www.cnblogs.com/Blackops/p/5766315.html