POJ——3070Fibonacci(矩陣快速冪)

來源:互聯網
上載者:User

標籤:

Fibonacci
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 12329   Accepted: 8748

Description

In the Fibonacci integer sequence, F0 = 0, F1 = 1, and Fn = Fn − 1 + Fn − 2 for n ≥ 2. For example, the first ten terms of the Fibonacci sequence are:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …

An alternative formula for the Fibonacci sequence is

.

Given an integer n, your goal is to compute the last 4 digits of Fn.

Input

The input test file will contain multiple test cases. Each test case consists of a single line containing n (where 0 ≤ n ≤ 1,000,000,000). The end-of-file is denoted by a single line containing the number −1.

Output

For each test case, print the last four digits of Fn. If the last four digits of Fn are all zeros, print ‘0’; otherwise, omit any leading zeros (i.e., print Fn mod 10000).

Sample Input

099999999991000000000-1

Sample Output

0346266875

Hint

As a reminder, matrix multiplication is associative, and the product of two 2 × 2 matrices is given by

.

Also, note that raising any 2 × 2 matrix to the 0th power gives the identity matrix:

.

 

看了很多關於矩陣快速冪的題解,感覺矩陣快速冪得到的是一個含有多個項的矩陣,而答案只是其中一項,而且之還需要特判指數。入門的矩陣快速冪題。感受一下再寫其它的題目。拿這題為例。題目中給出的項從0開始,F0=0,F1=1,F2=1,F3=2。。就是一個斐波那契的數列。由於用矩陣,那至少要兩項來組成矩陣,根據他的遞推公式。可以得到[Fn,Fn-1]=[1*Fn-1+1*Fn-2,1*Fn-1+0*Fn-2]

代碼:

#include<iostream>#include<algorithm>#include<cstdlib>#include<sstream>#include<cstring>#include<cstdio>#include<string>#include<deque>#include<stack>#include<cmath>#include<queue>#include<set>#include<map>using namespace std;typedef long long LL;#define INF 0x3f3f3f3fstruct mat {LL m[2][2];mat(){memset(m,0,sizeof(m));}};mat cheng(mat a,mat b){mat c;for (int i=0 ;i<2; i++){for (int j=0; j<2; j++){for (int k=0; k<2; k++){c.m[i][j]+=(a.m[i][k]*b.m[k][j])%10000;}}}return c;}mat zxc(mat a,LL b){mat c;c.m[0][0]=c.m[1][1]=1;while (b!=0){if(b&1)c=cheng(c,a);a=cheng(a,a);b>>=1;}return c;}int main(void){LL n;while (cin>>n&&n!=-1){mat one;if(n==0){cout<<0<<endl;continue;}else if(n==1){cout<<1<<endl;continue;}one.m[0][0]=one.m[1][0]=one.m[0][1]=1;one=zxc(one,n-1);cout<<one.m[0][0]%10000<<endl;;}return 0;}

  

 

POJ——3070Fibonacci(矩陣快速冪)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.