矩陣快速冪 Fibonacci 3070 poj

來源:互聯網
上載者:User

 題意為已知F0 =
0, F1 = 1, and Fn = Fn −
1 + Fn − 2 for n ≥
2.

求Fn%10000.

這裡運用到了矩陣快速冪的方法。

快速冪歸根結底就是:把a^k中的k拆分為2進位

例如:

 5^5=5^(1*1+0*2+1*4)=5^1*5^4. 計算量從算5次減少到了2次。

快速冪再結合矩陣,可以快速解決遞推問題

Fn = Fn −
1 + Fn − 2 中

已知:


所以矩陣做n次冪,就相當於遞推式往後推n次。

#include<iostream>#include<cstring>using namespace std;void Mul(int a[2][2],int b[2][2],int c[2][2])//矩陣的乘法運算{int i,j,k;int sum;for(i=0;i<2;i++)for(j=0;j<2;j++){sum=0;for(k=0;k<2;k++)sum+=(a[i][k]*b[k][j])%10000;c[i][j]=sum%10000;}}void Pow(int a[2][2],int n){if(n==1)return ;int b[2][2],c[2][2];memcpy(b,a,sizeof(b));Pow(b,n/2);//n的最後一位是1,舉個例子說明a^11101=a^( (1110*2) +1)=(a^1110)*(a^1110)*aif(n%2){Mul(b,a,c);Mul(c,b,a);}elseMul(b,b,a);}int main(){int n;while(cin>>n!=0&&n>=0){int a[2][2]={//初始化矩陣{1,1},{1,0}};if(n==0)cout<<"0"<<endl;else{Pow(a,n);cout<<a[0][1]<<endl;}}return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.