您的位置:首页 > 其它

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

2017-06-30 14:29 567 查看


M斐波那契数列

Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others)

Total Submission(s): 3404    Accepted Submission(s): 1056


Problem Description

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

F[0] = a

F[1] = b

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

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

 

Input

输入包含多组测试数据;

每组数据占一行,包含3个整数a, b, n( 0 <= a, b, n <= 10^9 )

 

Output

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

 

Sample Input

0 1 0
6 10 2

 

Sample Output

0
60

 

思路:如果F(5,6)代表a^5*a^6,那么F1=(1,0),F2=(0,1),F3(1,1),F4=(1,2)........可以发现括号里的两个数值分别符合斐波那契数列和类斐波那契数列。这样可以求得结果A,B的指数,通过费马小定理降幂,再通过快速幂计算出结果。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
#define ms(a,b)memset(a,b,sizeof(a))
#define eps 1e-10
#define inf 1e8

typedef long long ll;
typedef vector<ll> vec;
typedef vector<vec> mat;

const ll M=1000000007;
mat mul(mat &A,mat &B)
{
mat C(A.size(),vec(B[0].size()));
for(int i=0;i<A.size();i++)
for(int k=0;k<B.size();k++)
for(int j=0;j<B[0].size();j++)
C[i][j]=(C[i][j]+A[i][k]*B[k][j])%(M-1);
return C;
}

mat pow(mat A,ll n)
{
mat B(A.size(),vec(A.size()));
for(int i=0;i<A.size();i++)
B[i][i]=1;
while(n>0)
{
if(n&1) B=mul(B,A);
A=mul(A,A);
n>>=1;
}
return B;
}

ll mod_pow(ll x,ll n)
{
ll ans=1;
while(n>0)
{
if(n&1) ans=(ans*x)%M;
x=x*x%M;
n>>=1;
}
return ans;
}

int main()
{
ll a,b,n;
while(~scanf("%lld%lld%lld",&a,&b,&n))
{
mat A(2,vec(2));
A[0][0]=A[0][1]=A[1][0]=1;
A[1][1]=0;
A=pow(A,n);
ll x1=A[1][0];
ll x2=A[1][1];
ll ans=mod_pow(a,x2)*mod_pow(b,x1);
ans%=M;
printf("%lld\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: