Fibonacci
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 7138 | Accepted: 5044 |
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:
.
Source
1 #include <iostream> 2 #include <cstring> 3 4 #define MOD 10000 5 6 typedef long long LL[2][2]; 7 8 using namespace std; 9 10 void mul(LL a,LL b,LL c) 11 { 12 c[0][0]=((a[0][0]%MOD*b[0][0]%MOD)%MOD+(a[0][1]%MOD*b[1][0]%MOD)%MOD)%MOD; 13 c[0][1]=((a[0][0]%MOD*b[0][1]%MOD)%MOD+(a[0][1]%MOD*b[1][1]%MOD)%MOD)%MOD; 14 c[1][0]=((a[1][0]%MOD*b[0][0]%MOD)%MOD+(a[1][1]%MOD*b[1][0]%MOD)%MOD)%MOD; 15 c[1][1]=((a[1][0]%MOD*b[0][1]%MOD)%MOD+(a[1][1]%MOD*b[1][1]%MOD)%MOD)%MOD; 16 } 17 18 19 20 int main() 21 { 22 int n; 23 while(cin>>n&&n!=-1) 24 { 25 LL e={1,0,0,1}; 26 LL c={1,1,1,0}; 27 LL t; 28 while(n) 29 { 30 for(; n; n >>= 1) 31 { 32 if(n&1) 33 { 34 mul(e,c,t); 35 memcpy(e,t,sizeof(t)); 36 } 37 mul(c,c,t); 38 memcpy(c,t,(sizeof(t))); 39 } 40 } 41 42 cout<<e[0][1]<<endl; 43 } 44 45 46 return 0; 47 }