标签:
在“1250 Fibonacci数列”中,我们求出了第n个Fibonacci数列的值。但是1250中,n<=109。现在,你的任务仍然是求出第n个Fibonacci数列的值,但是注意:n为整数,且1 <= n <= 100000000000000
输入有多组数据,每组数据占一行,为一个整数n(1 <= n <= 100000000000000)
输出若干行。每行输出第(对应的输入的)n个Fibonacci数(考虑到数会很大,mod 1000000007)
3
4
5
2
3
5
1 <= n <= 100000000000000
1 #include<cstdio> 2 #include<cstring> 3 #include<iostream> 4 #include<algorithm> 5 using namespace std; 6 long long table[2][2],a[2][2],h[2][2]; 7 int q=1000000007; 8 void fang() 9 { int i,j,k; memset(a,0,sizeof(a)); 10 for (i=0;i<=1;++i) 11 for (j=0;j<=1;++j) 12 for (k=0;k<=1;++k) 13 a[i][j]=(a[i][j]+table[i][k]*table[k][j])%q; 14 } 15 void chengxa() 16 { int i,j,k; memset(h,0,sizeof(h)); 17 table[0][0]=0;table[0][1]=1;table[1][0]=1;table[1][1]=1; 18 for (i=0;i<=1;++i) 19 for (j=0;j<=1;++j) 20 for (k=0;k<=1;++k) 21 h[i][j]=(h[i][j]+table[i][k]*a[k][j])%q; 22 for (i=0;i<=1;++i) for (j=0;j<=1;++j) table[i][j]=h[i][j]; 23 } 24 void changeback() 25 { int i,j; 26 for (i=0;i<=1;++i) for (j=0;j<=1;++j) table[i][j]=a[i][j]; 27 } 28 void cheng(long long x) 29 { 30 if (x<=1) return; 31 cheng(x/2); 32 fang(); 33 if (x%2==1) chengxa(); 34 else changeback(); 35 } 36 int main() 37 { 38 long long n; 39 while (cin>>n) 40 { 41 table[0][0]=0;table[0][1]=1;table[1][0]=1;table[1][1]=1; 42 cheng(n-1); printf("%lld\n",table[1][1]); 43 } 44 return 0; 45 }
codevs1732 Fibonacci数列 2 傻逼的不能再傻逼的矩乘,然而我还WA过!
标签:
原文地址:http://www.cnblogs.com/HeatingLine/p/5014081.html