http://acm.hdu.edu.cn/showproblem.php?pid=4549
分析:
写出F[n]的几项之后发现a和b的指数和斐波那契数列有关
具体的关系是 F[n]=a^fib[n-1] * b^fib[n]
矩阵快速幂求fib 快速幂求a和b的n次幂
题目要求对F[n]%mod 这里用到费马小定理
即: 假如p是质数,且gcd(a,p)=1,那么 a(p-1)≡1(mod p),即:假如a是整数,p是质数,且a,p互质(即两者只有一个公约数1),那么a的(p-1)次方除以p的余数恒等于1 (来自百度百科)
也就是说 ap %mod = ap%(mod-1)%mod
证明:
设 p=k*(mod-1)+r
则ap%mod=(ak*(mod-1) * ar)%mod=ar%mod=ap%(mod-1)%mod
AC代码:
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <math.h>
#include <bitset>
#include <algorithm>
#include <climits>
typedef long long LL;
const LL mod=1000000007;
using namespace std;
int n=2;
struct Matrix{
LL a[2][2];
void init(){
memset(a,0,sizeof(a));
for (int i=0;i<n;i++)
a[i][i]=1;
}
};
Matrix multiply(Matrix x,Matrix y){
Matrix temp;
memset(temp.a,0,sizeof(temp.a));
for (int i=0;i<n;i++){
for (int j=0;j<n;j++){
for (int k=0;k<n;k++){
temp.a[i][j]=(temp.a[i][j]+x.a[i][k]*y.a[k][j])%(mod-1);
}
}
}
return temp;
}
Matrix qpow(Matrix M,LL k){
Matrix temp;
temp.init();
while (k){
if (k%2)
temp=multiply(temp,M);
k/=2;
M=multiply(M,M);
}
return temp;
}
LL Power(LL a,LL b){
LL temp=1;
while (b){
if(b%2)
temp=(temp*a)%mod;
b/=2;
a=(a*a)%mod;
}
return temp%mod;
}
int main (){
LL a,b,N;
//freopen("data","r",stdin);
while (scanf ("%lld%lld%lld",&a,&b,&N)!=EOF){
Matrix M;
memset(M.a,0,sizeof(M.a));
M.a[0][0]=M.a[0][1]=M.a[1][0]=1;
if (N==0){
printf ("%lld\n",a);
continue;
}
if (N==1){
printf ("%lld\n",b);
continue;
}
LL p1,p2;
Matrix temp;
temp=qpow(M,N-1);
p1=temp.a[0][0];
p2=temp.a[1][0];
//printf ("%lld %lld\n",p1,p2);
printf("%lld\n",Power(a,p2)*Power(b,p1)%mod);
}
return 0;
}
本文介绍了解决HDU 4549题目的方法,利用矩阵快速幂求解斐波那契数列,并结合费马小定理进行取模运算,通过具体的AC代码实现展示了这一过程。
529

被折叠的 条评论
为什么被折叠?



