Fibonacci
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 7752 | Accepted: 5501 |
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
0 9 999999999 1000000000 -1
Sample Output
0 34 626 6875
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <stdio.h> 3 #include <string.h> 4 #include <math.h> 5 #include <stdlib.h> 6 7 using namespace std; 8 int N; 9 struct matrix 10 { 11 int a[2][2]; 12 }origin,res; 13 matrix multiply(matrix x,matrix y) 14 { 15 matrix temp; 16 memset(temp.a,0,sizeof(temp.a)); 17 for(int i=0;i<N;i++) 18 { 19 for(int j=0;j<N;j++) 20 { 21 for(int k=0;k<N;k++) 22 { 23 temp.a[i][j]+=x.a[i][k]*y.a[k][j]%10000; 24 temp.a[i][j]%=10000; 25 } 26 } 27 } 28 return temp; 29 } 30 void calc(int n) 31 { 32 memset(res.a,0,sizeof(res.a)); 33 origin.a[0][0]=1;origin.a[0][1]=1; 34 origin.a[1][0]=1;origin.a[1][1]=0; 35 for(int i=0;i<N;i++) 36 res.a[i][i]=1; 37 while(n) 38 { 39 if(n&1) 40 res=multiply(res,origin); 41 n>>=1; 42 origin=multiply(origin,origin); 43 } 44 } 45 int main() 46 { 47 N=2; 48 int n; 49 while(cin>>n) 50 { 51 if(n==-1) 52 break; 53 if(n) 54 calc(n-1); 55 if(n) 56 cout<<res.a[0][0]<<endl; 57 else cout<<0<<endl; 58 } 59 }