poj_3070 Fibonacci(矩阵快速幂)

来源:互联网 发布:淘宝金牌卖家有假货吗 编辑:程序博客网 时间:2024/06/05 12:48
Fibonacci
Time Limit: 1000MS Memory Limit: 65536KTotal Submissions: 13957 Accepted: 9886

Description

In the Fibonacci integer sequence, F0 = 0, F1 = 1, andFn = Fn − 1 + Fn − 2 forn ≥ 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 ofFn are all zeros, print ‘0’; otherwise, omit any leading zeros (i.e., printFn 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:

.

矩阵快速幂。


#include <iostream>#include <cstdio>#include <cstdlib>#include <cstring>#include <cmath>#include <stack>#include <bitset>#include <queue>#include <set>#include <map>#include <string>#include <algorithm>#define FOP freopen("data.txt","r",stdin)#define FOP2 freopen("data1.txt","w",stdout)#define inf 0x3f3f3f3f#define maxn 5#define PI acos(-1.0)#define LL long longusing namespace std;typedef long long Matrix[maxn][maxn];int sz = 4, mod = 10000;Matrix C;void matrix_mul(Matrix A, Matrix B, Matrix res) {  memset(C, 0, sizeof(C));  for(int i = 0; i < sz; i++)    for(int j = 0; j < sz; j++)      for(int k = 0; k < sz; k++) C[i][j] = (C[i][j] + A[i][k] * B[k][j]) % mod;  memcpy(res, C, sizeof(C));}Matrix a, r;void matrix_pow(Matrix A, int n, Matrix res) {  memcpy(a, A, sizeof(a));  memset(r, 0, sizeof(r));  for(int i = 0; i < sz; i++) r[i][i] = 1;  while(n) {    if(n&1) matrix_mul(r, a, r);    n >>= 1;    matrix_mul(a, a, a);  }  memcpy(res, r, sizeof(r));}Matrix A, res;int n;int main(){    A[0][0] = A[0][1] = A[1][0] = 1;    A[1][1] = 0;    while(~scanf("%d", &n) && n != -1)    {        matrix_pow(A, n, res);        printf("%d\n", res[0][1]);    }    return 0;}


0 0