题目链接:M斐波那契数列
解题思路:他和普通的斐波那契数列相似,但是是乘法,所以还要变形下,我们写几个式子就会发现一些规律
F(2) = a^1 * b^1
F(3) = a^1 * b^2
F(4) = a^2 * b^3
F(5) = a^3 * b^5
我们发现这里a和b的幂是斐波那契数列,所以我们可以用矩阵快速幂来算,这里要用到费马小定理a^p ≡ a(mod p)这里P是整数,所以对于mod P来说 a^(p - 1 + n) ≡ a^n (mod p),也就是幂对于p-1取模。幂算出来后分别带到a,b中快速幂,最后取个余数就好了,对于n < 2 的就直接输出就好了。
#include<cstdio>
#include<cstring>
#include<iostream>
#define MOD 1000000007
#define MAXN 2
#define MAXM 2
#define ll __int64
using namespace std;
struct Matrix{
int n, m;
ll a[MAXN][MAXM];
void clear(){
n = m = 0;
memset(a, 0, sizeof(a));
}
Matrix operator *(const Matrix &b) const{
Matrix tem;
tem.clear();
tem.n = n, tem.m = m;
for(int i = 0; i < n; i++){
for(int j = 0; j < b.m; j++){
for(int k = 0; k < m; k++){
tem.a[i][j] = (tem.a[i][j] + (a[i][k] * b.a[k][j] % (MOD - 1))) % (MOD - 1);
}
}
}
return tem;
}
void display(){
int i, j;
for(i = 0; i < n; i++){
for(j = 0; j < n; j++){
cout << a[i][j] << " ";
}
cout << endl;
}
}
};
ll a, b, n, x, y;
Matrix ans, q;
void quick_Matrix(int x){
int i, j, k;
ans.n = ans.m = 2;
q.n = q.m = 2;
for(i = 0; i < 2; i++){
for(j = 0; j < 2; j++){
ans.a[i][j] = i == j ? 1 : 0;
q.a[i][j] = 1;
}
}
q.a[1][1] = 0;
while(x){
if(x & 1){
ans = ans * q;
}
q = q * q;
x >>= 1;
}
}
ll calc(ll x, ll y){
ll q = x, ret = 1;
while(y){
if(y & 1){
ret = ret * q % MOD;
}
q = q * q % MOD;
y >>= 1;
}
return ret % MOD;
}
int main(){
int i, j, k;
while(cin >> a >> b >> n){
if(n == 0){
cout << a << endl;
continue;
}
if(n ==1){
cout << b << endl;
continue;
}
if(n == 2){
x = y = 1;
}
else if(n == 3){
x = 1;
y = 2;
}
else{
quick_Matrix(n - 3);
//ans.display();
x = (ans.a[0][0] + ans.a[0][1]) % (MOD - 1);// a
y = (x + ans.a[0][0]) % (MOD - 1);// b
//cout << x << " " << y << endl;
//cout << calc(a, x) << endl;
//cout << calc(b, y) << endl;
}
cout << (calc(a, x) * calc(b, y)) % MOD << endl;
}
return 0;
}