您的位置:首页 > 其它

E - M斐波那契数列 (费马小定理 + 二分快速幂 + 矩阵快速幂)

2017-08-15 16:48 363 查看
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(0)=a,F(1)=b

F(n)=F(n−1)F(n−2)

⇒F(n)=F(n−2)2F(n−3)

⇒F(n)=F(n−3)3F(n−4)2

⇒F(n)=F(n−4)5F(n−5)3



⇒F(n)=F(1)f(n)F(0)f(n−1)

⇒F(n)=bf(n)af(n−1)

f(n)正是斐波那契数列。

矩阵快速幂可以求出f(n),f(n−1)的值。

然后快速幂计算bf(n),af(n−1), 答案就是两者乘积。

需要注意一点,取模是对F(n)取模,不是f(n),那么问题来了,f(n)会是一个很大的数,如果不模一下根本存不下,怎么办呢?

这里的模 p=1000000007,是个素数,由欧拉定理,

a^x≡a^(x%(p-1))(mod p)

所以f(n)可以对 p−1取模。

斐波那契数列就用矩阵快速幂去求:

最后再快速幂取模

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
const int mod=1000000007;
typedef long long LL;
LL a,b;
int n;
LL pow(LL a,LL b){
LL res=1;
while(b){
if(b&1)
res=(res*a)%mod;
a=(a*a)%mod;
b>>=1;
}
return res;
}
LL mul(int n){
LL t[2][2]={1,1,1,0};
LL ans[2][2]={1,0,0,1};
LL temp[2][2];
while(n){
if (n&1){
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
temp[i][j]=ans[i][j],ans[i][j]=0;
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
for(int k=0;k<2;k++)
ans[i][j]=(ans[i][j]+temp[i][k]*t[k][j])%(mod-1);
}
for(int i=0;i<2;i++)
for(int j=0;j<2;j++){
temp[i][j]=t[i][j]; t[i][j]=0;
}
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
for(int k=0;k<2;k++)
t[i][j]=(t[i][j]+temp[i][k]*temp[k][j])%(mod-1);
n>>=1;
}
return (pow(a,ans[1][1])*pow(b,ans[1][0]))%mod;
}

int main()
{
while(scanf("%lld%lld%d",&a,&b,&n)!=EOF){
if(n==0)
printf("%lld\n",a%mod);
else if(n==1)
printf("%lld\n",b%mod);
else
printf("%lld\n",mul(n));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: