1. 程式人生 > >hdu-4549 M斐波那契數列【矩陣快速冪】

hdu-4549 M斐波那契數列【矩陣快速冪】

找規律寫出f(2),f(3),f(4),f(5) .........可以發先 a b的係數是一系列的fib數列   如果可以求出fib數列 求快速冪就可以了    這樣問題就在於如何求fib數列了

                          1     1

【f[n-1],f[n-2]】 *  1     0     =  【f[n],f[n-1]】

 當gcd(A,M)==1的時候 
A^X = A^( X mod Eular(M) ) ( mod M ) .
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <vector>
#define L 2
using namespace std;
typedef long long int llint;
typedef vector<llint> vec;
typedef vector<vec> mat;
const llint MOD=1000000007;
struct Matrix
{
	llint m[L][L];
};
Matrix matrix_mul(Matrix a,Matrix b)
{
	Matrix res;
	for(int i=0;i<L;++i)
		for(int j=0;j<L;++j)
		{
			res.m[i][j]=0;
			for(int k=0;k<L;++k)
			{
				res.m[i][j]+=a.m[i][k]*b.m[k][j];
				res.m[i][j]%=MOD-1;
			}
		}
	return res;
}
Matrix Mquickpow(Matrix p,llint n)
{
	Matrix res;
	res.m[0][0]=res.m[1][1]=1;
	res.m[0][1]=res.m[1][0]=0;
	while(n>0)
	{
		if(n&1)
			res=matrix_mul(p,res);
		n=n>>1;
		p=matrix_mul(p,p);
	}
	return res;
}
llint quickpow(llint a,llint n)
{
	llint res=1;
	a%=MOD;
	while(n>0)
	{
		if(n&1)
			res=res*a%MOD;
		n=n>>1;
		a=a*a%MOD;
	}
	return res;
}
int main()
{
	llint a,b,n;
	Matrix t;
	t.m[0][0]=0,t.m[0][1]=t.m[1][0]=t.m[1][1]=1;
	while(~scanf("%lld%lld%lld",&a,&b,&n))
	{
		if(n==0)
			printf("%lld\n",a%MOD);
		else if(n==1)
			printf("%lld\n",b%MOD);
		else
		{
			Matrix res=Mquickpow(t,n-2);
			llint f0=(res.m[0][0]+res.m[0][1])%(MOD-1);
			llint f1=(res.m[1][0]+res.m[1][1])%(MOD-1);
			llint ans=(quickpow(a,f0)%MOD)*(quickpow(b,f1)%MOD);
			ans%=MOD;
			printf("%lld\n",ans);
		}
	}
	return 0;
}