HDU4549 M斐波那契数列 —— 斐波那契、费马小定理、矩阵快速幂

时间:2023-11-25 17:58:44

题目链接:https://vjudge.net/problem/HDU-4549

M斐波那契数列

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

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
Source
Recommend
liuyiding

题解:

1.可知f[n]中a、b的指数符合斐波那契数列,因而可用矩阵快速幂求出。

2.然而如果指数不求模,也可能会溢出。但指数又怎样求模呢?

有如下定理:当m为素数,且a、n互质时, a^n % m = a^(n%(m-1)) % m

证明:

根据费马小定理,当m为素数,且a、p互质时, a^(m-1) ≡ 1 (mod m),

a^n = a^(k*(m-1)+r) = (a^(m-1))^k * a^r,其中 r = n%(m-1),

那么 a^n % m = ( (a^(m-1))^k * a^r ) % m =  (a^(m-1))^k % m * a^r % m = 1 * a^r % m = a^(n%(m-1)) % m 。

所以:当m为素数,且a、n互质时, a^n % m = a^(n%(m-1)) % m

代码如下:

 #include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <string>
#include <set>
using namespace std;
typedef long long LL;
const int INF = 2e9;
const LL LNF = 9e18;
const int MOD = ;
const int MAXN = 1e6+; const int Size = ;
struct MA
{
LL mat[Size][Size];
void init()
{
for(int i = ; i<Size; i++)
for(int j = ; j<Size; j++)
mat[i][j] = (i==j);
}
}; MA mul(MA x, MA y)
{
MA ret;
memset(ret.mat, , sizeof(ret.mat));
for(int i = ; i<Size; i++)
for(int j = ; j<Size; j++)
for(int k = ; k<Size; k++)
ret.mat[i][j] += (1LL*x.mat[i][k]*y.mat[k][j])%(MOD-), ret.mat[i][j] %= (MOD-);
return ret;
} MA qpow(MA x, LL y)
{
MA s;
s.init();
while(y)
{
if(y&) s = mul(s, x);
x = mul(x, x);
y >>= ;
}
return s;
} LL q_pow(LL x, LL y)
{
LL s = ;
while(y)
{
if(y&) s *= x, s %= MOD;
x *= x, x %= MOD;
y >>= ;
}
return s;
} MA tmp = {
, ,
,
}; int main()
{
LL f[], n;
while(scanf("%lld%lld%lld",&f[],&f[],&n)!=EOF)
{
if(n<=)
{
printf("%lld\n", f[n]%MOD);
continue;
} MA s = tmp;
s = qpow(s, n-);
LL p1 = s.mat[][];
LL p2 = s.mat[][];
LL ans = q_pow(f[], p2)*q_pow(f[], p1)%MOD;
printf("%lld\n", ans);
}
}