M斐波那契数列
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others)Total Submission(s): 2843 Accepted Submission(s): 853
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]的值吗?
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 )
每组数据占一行,包含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
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
const int mod = 1e9+7;
using namespace std;
long long a,b,c;
inline long long q_pow(long long x,long long y){
long long res = 1;
x %= mod;
while(y){
if(y&1){
res = res * x % mod;
}x = x * x % mod;
y>>=1;
}return res ;
}
inline long long work(){
if(c==0){
return a;
}if(c==1){
return b;
}c--;
long long t[2][2]={1,1,1,0};
long long res[2][2]={1,0,0,1};
long long tmp[2][2];
while(c){
if(c&1){
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){
tmp[i][j] = res[i][j];
}
}memset(res,0,sizeof(res));
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){
for(int k=0;k<2;k++){
res[i][j] = (res[i][j]+tmp[i][k]*t[k][j])%(mod-1);
}
}
}
}
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){
tmp[i][j] = t[i][j];
}
}memset(t,0,sizeof(t));
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] + tmp[i][k] * tmp[k][j] )%(mod-1);
}
}
}c>>=1;
}
return q_pow(b,res[0][0])*q_pow(a,res[0][1])%mod;
}
int main()
{
while(cin>>a>>b>>c){
cout<<work()<<endl;
}return 0;
}