# [POJ 3070] Fibonacci【矩乘优化】

• 2018-01-07
• 0
• 0

## Problem:

 Time Limit: 1000MS Memory Limit: 65536K

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```

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

Stanford Local 2006

## Solution:

You're too young ~~ too simple ~~ too naive ~~

## Code: O(Ts3logn), s为矩阵阶数(=2) [144K, 16MS]

```#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<cassert>
#include<iostream>
#include<algorithm>
using namespace std;
const int MOD = 10000;

int n;

struct Matrix{
int ele[3][3], size;

inline void setIdentity(int idensize){
memset(ele, 0, sizeof(ele));
size = idensize;
for(register int i = 1; i <= size; i++)
ele[i][i] = 1;
}

inline Matrix operator * (const Matrix &mat2) const {
assert(size == mat2.size);  // Or the multiplication isn't defined
Matrix res; res.size = size;
for(register int i = 1; i <= size; i++)
for(register int j = 1; j <= mat2.size; j++){
res.ele[i][j] = 0;
for(register int k = 1; k <= size; k++)
res.ele[i][j] = (res.ele[i][j] + ele[i][k] * mat2.ele[k][j]) % MOD;
}
return res;
}

inline Matrix pow(int ex){
Matrix bas = *this, res; res.setIdentity(size);
while(ex){
if(ex & 1) res = res * bas;
ex >>= 1, bas = bas * bas;
}
return res;
}
} Fib;

int main(){
while(scanf("%d", &n) != EOF && n != -1){
if(n < 2){
if(n) puts("1"); else puts("0");
continue;
}
Fib.size = 2;
Fib.ele[1][1] = 1, Fib.ele[1][2] = 1;
Fib.ele[2][1] = 1, Fib.ele[2][2] = 0;
Fib = Fib.pow(n - 1);
printf("%d\n", Fib.ele[1][1]);
}
return 0;
}
```

#### 评论

darkleafin.cf
(该域名已过期且被抢注。。)
darkleafin.github.io

49750

https://github.com/Darkleafin

OPEN AT 2017.12.10

Please refresh the page if the code cannot be displayed normally.

https://visualgo.net/en

- Theme by Qzhai